Unlikenesses A Backend Developer

redux with local storage

31 July 2017

I'm in the process of converting the React version of DruMVC to use Redux. It was pretty straightforward until I got to the bits that used localStorage, the browser-based storage object. The "vanilla"-React version uses the componentWillMount and componentWillUpdate lifecycle hooks to get and set, respectively, the localStorage data. I.e. when the App component loads, it checks if localStorage contains any data (in the case of DruMVC, this data is just the configuration of on/off notes for each track), and if so it updates the state accordingly. Similarly, when the state changes, the App component will save it to localStorage. You can see the code here.

But now that the state, under Redux, is no longer a property of the App component, how and when do we call the relevant getItem and setItem commands?

This SO answer by Redux co-author Dan Abramov suggests using subscribe to set localStorage and to get it by passing it as an argument to createStore. His video shows in more detail how to do this. Briefly, following the video, I create a new module, localStorage.js, with two methods, loadState and saveState. In my index.js I then pass the loaded state to createStore, and set up a subscribe listener, which saves a subsection of the state.