Persisting the Store

Your Quotebase app lets you view and add quotations. But it lacks an important feature: none of the quotations you add will stick around if you close the page. You must fix this.

The browser provides a facility called local storage that lets you store multiple megabytes of string data. Whenever the global store changes, you want to save the current state. You could add code to your two actions to store the state, but there's a more direct way to run a callback whenever the state changes. You open up store.js, add an event listener using the subscribe method, serialize the store, and write it to local storage under the key quotebase.db:

// ...

store.subscribe(() => {
const json = JSON.stringify(store.getState());
localStorage.setItem('quotebase.db', json);
});

When the app loads, you want to prime the state with any previously persisted state. You deserialize it using JSON.parse. If there is no persisted state, you use the original initial state:

// ...

const persistedState = JSON.parse(localStorage.getItem('quotebase.db'));
export const store = createStore(reducer, persistedState ?? initialState);

// ...

Try adding quotations to the store and closing the page. When you revisit, do the new quotations still appear?