Jiwan Kim
Jiwan Kim

Reputation: 1

setState doesnt work when using object which has been copied from spread operator

I have the following codes and it doesn't work and only shows me "undefined" value of orientation object as same as before.

let insertDataObj = {...this.state.orientation};
insertDataObj.startTime = "03";
this.setState({
    orientation: insertDataObj,
});

however, following codes works like a charm and shows me the "03" value of orientation object as I intended.

let insertDataObj = this.state.orientation.
insertDataObj.startTime = "03";
this.setState({
    orientation: insertDataObj,
});

So, I am quite confused with the result. I heard that copying object using spread operator should be way more secure and cleaner code than simple copy method and I really thought it would be working as a charm but it doesn't work. Why is that?

Upvotes: 0

Views: 48

Answers (1)

Daniel Duong
Daniel Duong

Reputation: 1104

Hi It looks like you did not spread the state properly; When you spread { ...this.state.orientation } you get an object that looks like this.

{ startTime: "02" };
rather than
{ orientation: { startTime: "02" } };
You should have done
{ ...this.state };

Also it would be a really good idea to use functional setState to reduce code and potential mutation like so.

this.setState((state) => ({
   orientation: { ...state.orientation, startTime: "03" },
}));

Upvotes: 1

Related Questions