Step 7: Make Todos persistent with local storage

Let’s revisit the issue of items not persisting when the browser refreshes with our React/Redux mytodo app.

If the persistence is not a issue for you or you're short on time, you can skip this step and jump directly to the Step 8 "Get ready for production".

.

Install npm package

To easily achieve this, we can use another Redux module called “redux-localstorage” that will allow us to quickly implement local storage.

Run the following command:

npm install --save redux-localstorage@rc

Use redux-localstorage

The Redux store should be configured to use storage. Replace the whole your src/app/store/configureStore.js by this code:

import {compose, createStore} from 'redux';
import rootReducer from '../reducers';

import persistState, {mergePersistedState} from 'redux-localstorage';
import adapter from 'redux-localstorage/lib/adapters/localStorage';

export default function configureStore(initialState) {
  const reducer = compose(
    mergePersistedState()
  )(rootReducer, initialState);

  const storage = adapter(window.localStorage);

  const createPersistentStore = compose(
    persistState(storage, 'state')
  )(createStore);

  const store = createPersistentStore(reducer);
  if (module.hot) {
    // Enable Webpack hot module replacement for reducers
    module.hot.accept('../reducers', () => {
      const nextReducer = require('../reducers').default;
      store.replaceReducer(nextReducer);
    });
  }

  return store;
}

If you look at your app in the browser, you’ll see that there are one item “Use Yeoman” in the todo list. The app is initialising the todos store if local storage is empty and we haven’t given it any todo items yet.

Go ahead and add a few items to the list:

Now when we refresh our browser the items persist. Hooray!

We can confirm whether our data is being persisted to local storage by checking the Resources panel in Chrome DevTools and selecting Local Storage from the lefthand side:

Write unit tests

For an extra challenge, revisit unit testing in Step 6 and consider how you might update your tests now that the code is using local storage.

« Return to overview or Go to the next step »