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?
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.
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.
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.
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)) }); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With