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
JavaScript
x
20
20
1
constructor(props){
2
super(props);
3
4
this.state ={
5
value: 1,
6
toggled: undefined
7
};
8
this.handleToggle = this.handleToggle.bind(this);
9
}
10
11
handleToggle = (event,toggled,index) => {
12
this.setState({toggled});
13
14
if (toggled == true){
15
///sync the Calendar code////
16
}else{
17
/// un sync ////
18
}
19
}
20
and here after return
JavaScript
1
5
1
<Toggle label={translate('sync')}
2
onToggle={this.handleToggle}
3
toggled={this.state.toggled}
4
/>
5
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
JavaScript
1
26
26
1
constructor(props){
2
super(props);
3
const local = localStorage.getItem('state');
4
if(local) {
5
this.state =JSON.parse(local)
6
} else {
7
this.state ={
8
value: 1,
9
toggled: undefined
10
};
11
this.handleToggle = this.handleToggle.bind(this);
12
}
13
}
14
15
handleToggle = (event,toggled,index) => {
16
this.setState({toggled});
17
if (toggled == true){
18
///sync the Calendar code////
19
}else{
20
/// un sync ////
21
}
22
23
componentWillUnmount() {
24
localStorage.setItem('state', JSON.stringify(this.state));
25
}
26