In some situations, I want to validate data in a React application by comparing the current state with the original data obtained from the API. I have issues preserving the original data when I need to modify a nested element inside an array.
For example, with this data:
{
id: 1,
items: [{name: "foo"}, {name: "bar"}]
}
And the following React component excerpt:
constructor(props) {
super(props);
this.state = {
originalData: null,
items: [],
};
}
componentDidMount() {
Api.get("/data").then(res => {
this.setState({
originalData: res.data,
items: res.data.items,
}
});
}
If this.state.items[0] becomes {name: "baz"}, this.state.originalData.items[0] will also be modified. I tried to use res.data.items.slice() and [...res.data.items] to make a copy of the array when setting the this.state.items but it did not help.
The two solutions I can see are:
- Call the API to get the original data when it's time to validate the current state
- Use
JSON.parse(JSON.stringify(res.data))to store a new object not referencingres.datainsidethis.state.originalData.
Is there a more elegant solution?