[Redux] Persisting the state to the Local Storage

Source: Internet
Author: User
Tags try catch

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.