React how to clone object from state to another state

Viewed 177

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

4 Answers

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

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

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

You could try a completely different approach -

  1. User goes into edit mode
  2. All edits are stored in separate temporary state. For example: this.state.draft = ...
  3. Original state is overwritten with Draft state only if user clicks "Save"
  4. All Draft state is discarded if user clicks "Cancel"
Related