Young L.
Young L.

Reputation: 1042

React how to clone object from state to another state

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

Answers (4)

iamwebkalakaar
iamwebkalakaar

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

Guest
Guest

Reputation: 11

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"

Upvotes: 1

Mechanic
Mechanic

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

ageoff
ageoff

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

Related Questions