Updating a post. I know that objects in JavaScript are referenced type. The handleUpdate method, takes in a post object, in that lecturer, Mosh directly modified the object. Since objects are reference type, modifying this object directly modifies the state. The state of a component should never be directly modified. I thought we were supposed to clone the object, and update the cloned copy and then pass the modified copy to the setState method to update the state
1 Like
I have the same concern, I feel it should be a mistake as otherwise it does not make sense with the guideline that one should not directly change the state.
@maverick @sufian.babri can you please share any idea that you might have regarding this?
For reference, following is the code snippet that the query is about:
handleUpdate = async post => {
post.title = "UPDATED";
await axios.put(apiEndpoint + '/' + post.id, post);
const posts = [...this.state.posts];
const index = posts.indexOf(post);
posts[index] = { ...post };
this.setState({ posts });
};
I think it should be something like the following where we are not directly changing the state:
handleUpdate = async post => {
let postToUpdate = {...post};
postToUpdate.title = 'Updated';
await axios.put(apiEndpoint + '/' + post.id, postToUpdate);
const posts = [...this.state.posts];
const index = posts.indexOf(post);
posts[index] = postToUpdate;
this.setState({ posts });
};
If the post
passed to handleUpdate
is from the state then changing it’s title would directly change the state, yes.
In case you are unsure you can set a breakpoint after the suspicious command and examine the state.
thanks @SAM. Yes, I did check and the state was getting affected (updated) by that command.