4

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.

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 because it'll be just state of component and not of my app.

halfer
  • 19,824
  • 17
  • 99
  • 186
K.Rice
  • 599
  • 1
  • 8
  • 27
  • Possible duplicate of [Where to write to localStorage in a Redux app?](https://stackoverflow.com/questions/35305661/where-to-write-to-localstorage-in-a-redux-app) – Jim G. Jul 05 '18 at 12:10

2 Answers2

1

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:

localStorage.removeItem('nameForData')

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

alex
  • 5,467
  • 4
  • 33
  • 43
  • Thanks for answer. I'm glad it's possible without additional modules like redux-localstorage. – K.Rice Aug 04 '16 at 11:48
1

I can suggest you to store the state after each action. For that you can use a localStorage middleware that only store the whole state object.

Then in your createStore part you will retrieve the initialState from the localStorage API.

In that case you don't need to modify any component, juste the initialState from localStorage and the middleware that save the state

Michael Rasoahaingo
  • 1,069
  • 6
  • 11