DEV Community

Avichay Eyal
Avichay Eyal

Posted on

Undying objects in javascript

I'd like to introduce a simple and effective tool I have just published that creates an observable state with an "auto-save to local-storage" feature.

Every change (or changeset) in the object's tree will flush the data as JSON object into the local storage, and be restored on the next page load.

import { undying } from 'undying';


const defaultValues = {
    favouriteColor: 'blue',
};

const undyingObject = undying('user-defaults', defaultValues);
/* If the data exists on the local storage,
   the default values will be ignored and actual data is restored.
   If the data does not exist,
   it will be created with default values
*/


undyingObject.favouriteColor = 'red';
undyingObject.shape = 'rectangle';
// async flush to local storage.

Enter fullscreen mode Exit fullscreen mode

You can also be notified when something is changed:

const myState = undying({});
undying.observe(undyingObject, (value) => {
    // value is the whole tree data
});
Enter fullscreen mode Exit fullscreen mode

Enjoy.

https://www.npmjs.com/package/undying

Top comments (0)