K.Rice K.Rice - 2 months ago 30x
React JSX Question

LocalStorage with react-redux

I'm using react and redux for my SPA and I want to store some data locally. And I need to synchronize appState with localstorage, so my data won't be lost after refreshing the page. Help me, please. I'm completely new for react and redux and have not much of understanding what's going on, but as I think redux creates for me that state of entire app, so I can't just bind my state with localstorage in app component cuz it'll be just state of component and not of my app. (Some good tutorials, which can help me to understand life cycle of app will be appreciated too.)


I would suggest storing the data in local storage with the following commands.

Set the data in localStorage can be done with the command:

localStorage.setItem('nameForData', variableNameForData);

To retrieve the data when required.

var variableNameForData = localStorage.getItem('nameForData')

To remove the data from localStorage:


These would typically be put inside action creators with a dispatch to change the state of some Boolean that tracks the applications interaction with localStorage.

For example you might have a state that is set to true when the local storage is created.

On refresh you might call an action creator that checks the local storage exists, and if it does set that boolean back to true or if it does not exist you are back to creating local storage and then set it to true.

You could put this function in componentWillMount(){} and it will be called when the component is first rendered, and thus in the case of a refresh.

Docs for component life cycle and specifically componentWillMount here

Docs for local storage here