Reputation: 763
I am trying to set state value based on result of a promise method. For optimistic updates I am setting state value before an asynchronous operation. If operation fails state is reset
componentWillMount(){
this.setState({notify: this.props.notif});
}
render(){
return(
<Switch
onValueChange={(val) => this.toggleNotifications(val)}
disabled={! this.props.connected}
value={this.state.notify}
/>
)
}
toggleNotifications(val: boolean){
this.setState({notify: val});
mmSetNotification(val).catch(() => this.setState({notify: !val}));
}
I am using async method to set notification value using network call which will update user object
async function mmSetNotification(checked: boolean) : Promise {
return new Promise((resolve, reject) => {
Meteor.call('setNotification', checked, (error, result) => {
if(error){
reject(error);
}else{
resolve();
}
});
});
}
Upvotes: 1
Views: 114
Reputation: 3375
Use this.setState
instead mutating this.state
NEVER mutate this.state directly, as calling setState() afterwards may replace the mutation you made. Treat this.state as if it were immutable.
toggleNotifications(val: boolean){
this.setState({notify: val});
mmSetNotification(val).catch(() => this.setState({notify: !val});
}
Upvotes: 1