I am new to React and I am trying to know when does the state object is affected when I do a copy to an object in it.
In the following code; The first scenario causes the state object to be updated, but the second NOT. I need to know what is the difference and Why this is happening?
import React, { Component } from "react";
export class Test extends Component {
state = {
counters: [
{ id: 1, desc: "Item1 default description" },
{ id: 2, desc: "Item2 default description" }
]
};
handleAction() {
const counters = { ...this.state.counters };
////First Scenario
console.log("Item description before updating:", counters[0].desc);
counters[0].desc = "Item1 description updated successfully!"; //<--This line makes the state updated
console.log("Item description after updating:", counters[0].desc);
console.log(
"Item description value in state object:",
this.state.counters[0].desc //Item value is updated in the state object.
);
////Second Scenario
// console.log("Item description before updating:", counters[0].desc);
// counters[0] = { id: 1, desc: "Item1 description updated successfully!" }; //<--This line does NOT affect the state
// console.log("Item description after updating:", counters[0].desc);
// console.log(
// "Item description value in the state object:", //Item value is NOT updated in the state object.
// this.state.counters[0].desc
// );
}
render() {
return (
<React.Fragment>
{this.state.counters[0].desc}
<button
className="btn btn-danger btn-sm"
onClick={() => this.handleAction()}
>
Check Item description in state object
</button>
</React.Fragment>
);
}
}