简体   繁体   中英

How i can save the toggle state and don't lose after refresh the page

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 ?

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));
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM