Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to maintain state after a page refresh in React.js?

Lets say I have code that sets state for a select box chosen on the previous page:

this.setState({selectedOption: 5}); 

Is there any way to have this.state.selectedOption populated with 5 after a page refresh?

Are there callbacks that I can use to save this in localStorage and then do one large setState or is there a standard way of doing something like this?

like image 907
DiverseAndRemote.com Avatar asked Feb 04 '15 05:02

DiverseAndRemote.com


People also ask

Does Redux keep state after refresh?

With the Redux Persist library, developers can save the Redux store in persistent storage, for example, the local storage. Therefore, even after refreshing the browser, the site state will still be preserved.

How do I stop a refresh page from reacting?

Use the preventDefault() method on the event object to prevent a page refresh on form submit in React, e.g. event. preventDefault() . The preventDefault method prevents the browser from issuing the default action which in the case of a form submission is to refresh the page.


2 Answers

So my solution was to also set localStorage when setting my state and then get the value from localStorage again inside of the getInitialState callback like so:

getInitialState: function() {     var selectedOption = localStorage.getItem( 'SelectedOption' ) || 1;      return {         selectedOption: selectedOption     }; },  setSelectedOption: function( option ) {     localStorage.setItem( 'SelectedOption', option );     this.setState( { selectedOption: option } ); } 

I'm not sure if this can be considered an Anti-Pattern but it works unless there is a better solution.

like image 88
DiverseAndRemote.com Avatar answered Sep 26 '22 14:09

DiverseAndRemote.com


You can "persist" the state using local storage as Omar Suggest, but it should be done once the state has been set. For that you need to pass a callback to the setState function and you need to serialize and deserialize the objects put into local storage.

constructor(props) {   super(props);   this.state = {     allProjects: JSON.parse(localStorage.getItem('allProjects')) || []   } }   addProject = (newProject) => {   ...    this.setState({     allProjects: this.state.allProjects.concat(newProject)   },() => {     localStorage.setItem('allProjects', JSON.stringify(this.state.allProjects))   }); } 
like image 22
juliangonzalez Avatar answered Sep 23 '22 14:09

juliangonzalez