Reputation: 1042
Hi i would like to ask how can i copy object from react state to another temporary state. I tried it like this:
startEditing() {
this.setState({editMode: true});
//Save schedule before changes
this.setState({oldSchedule: this.state.schedule});
}
cancelEditing(){
this.setState({editMode:false});
//revert changes in schedule
this.setState({schedule:this.state.oldSchedule});
this.setState({oldSchedule:null});
}
I understan't why this no working but don't know how to do this properly. Could you help me please?
Schedule is object type
Upvotes: 3
Views: 577
Reputation: 358
The safest way you can try is this, no need to call multiple setState
startEditing() {
this.setState({});
//Save schedule before changes
this.setState({ oldSchedule: { ...this.state.schedule }, editMode: true });
}
cancelEditing() {
this.setState((prevState) => {
return {
editMode: false,
schedule: prevState.oldSchedule,
oldSchedule: null
}
});
}
Upvotes: 2
Reputation: 11
You could try a completely different approach -
this.state.draft = ...
Upvotes: 1
Reputation: 5380
because you are not copying previous object, you making another reference to it; you should deep copy that object; one-way is to use json.parse();
startEditing() {
this.setState({
editMode: true,
oldSchedule: JSON.parse(JSON.stringify(this.state.schedule))
});
}
cancelEditing(){
this.setState({
editMode:false,
schedule:JSON.parse(JSON.stringify(this.state.oldSchedule)),
oldSchedule:null
});
}
Upvotes: 1
Reputation: 2828
If schedule is an object then you should do a copy of the object instead of the object itself:
startEditing() {
this.setState({editMode: true});
//Save schedule before changes
this.setState({oldSchedule: {...this.state.schedule}});
}
cancelEditing(){
this.setState({editMode:false});
//revert changes in schedule
this.setState({schedule: {...this.state.oldSchedule}});
this.setState({oldSchedule:null});
}
Upvotes: 1