We'll learn how to use Store.subscribe () to efficiently persist some of the app's state to localstorage and restore it a Fter a refresh.
To save data on to Localstroge, we first create a Localstorgejs file and both methods, one for get and one for set:
Export Const LoadState = () = { //Important to use try catch for Localstorage if browser doesn ' t support local storge Try{Const Serializedstate= Localstorage.getitem (' state '); if(Serializedstate = = =NULL){ //If there is no item stored, then use default ES6 param returnundefined; }Else{ returnjson.parse (Serializedstate)}}Catch(err) {returnundefined; }}export Const SaveState= (state) = = { Try{Const Serializedstate=json.stringify (state); Localstorage.setitem (' State ', serializedstate); }Catch(Err) {Console.error ("Cannot save to storage"); }}
The data we want to save into Localstorage should is serializable. And should use try and catch to handle error.
Use LoadState () to get presisted data and to create store:
Const Persistedstate == CreateStore (Todoapp, persistedstate);
Subscribe to the store, everytime there are something changed, save the Todos into Localstorge:
Store.subscribe (() = { = store.getstate (); SaveState ({ todos })})
If already save some Todos into the Localstroge and refresh the app, then we find that we cannot save any todo anymore. This was because in the application we use ' nexttodoid ':
Let nexttodoid = 0= (text) = ( { ' Add_todo ', ID: (nexttodoid+ +). ToString (), text,});
Everytime page Refresh It'll start from zero again and then it cause the problem.
Install:
NPM I--save node-uuid
Node-uuid have a method call V4 () to generate a random ID:
////
We can use it to replace the old implemention:
Import {v4} from ' Node-uuid '= (text) = ( { ' Add_todo ', id:v4 (), text,});
One thing to being improved is everytime we update the Stroe, SaveState () function would be invoked. We want to add throttle to it:
Install:
NPM I--save Lodash
Import throttle from ' lodash/throttle '= == = = = store.getstate (); SaveState ({ todos 1000));
------------------------------
If look at the tests for CreateStore (), the second args can accpet ' undefined ', [], {}, fn and not null. So it's important to return ' undefined ' let reducer accept the ES6 default param.
See link:https://github.com/reactjs/redux/blob/master/test/createstore.spec.js#l546
[Redux] Persisting the state to the Local Storage