hello my project is done mostly from react and redux, i am buliding app in this app there is toggle when is on its sync the data to the calendar, and i want it to stay it toggle even after refresh the page. here is some code
constructor(props){ super(props); this.state ={ value: 1, toggled: undefined }; this.handleToggle = this.handleToggle.bind(this); } handleToggle = (event,toggled,index) => { this.setState({toggled}); if (toggled == true){ ///sync the Calendar code//// }else{ /// un sync //// } }
and here after return
<Toggle label={translate('sync')} onToggle={this.handleToggle} toggled={this.state.toggled} />
is there away to save the state taggle other than this.state ?
Advertisement
Answer
Save the state in localStorage on unmount and repopulate on initial mount
constructor(props){ super(props); const local = localStorage.getItem('state'); if(local) { this.state =JSON.parse(local) } else { this.state ={ value: 1, toggled: undefined }; this.handleToggle = this.handleToggle.bind(this); } } handleToggle = (event,toggled,index) => { this.setState({toggled}); if (toggled == true){ ///sync the Calendar code//// }else{ /// un sync //// } componentWillUnmount() { localStorage.setItem('state', JSON.stringify(this.state)); }