Hello guys, I'm learning React.

Hello guys, I'm learning React. Everyone is saying *don't change the state directly* instead clone the existing state, add changes to that and then use setState to make changes. But the *state gets changed directly If I make changes to a nested property of the cloned object.* I know cloning makes a shallow copy up to only one level but how do I achieve immutability? I can't get my head around this! Can you tell me how do you tackle this problem?
You already invited:

binkley

Upvotes from:

You will have to destructure the nested properties as well. JavaScript does not provide immutability out of the box. If you want immutability then you can look at libraries like immutable.js which gives you immutability. But if you are just starting out or just have a small app then it could be an overkill.

Marion

Upvotes from:

let deepClonedPost = JSON.parse(JSON.stringify(posts));
console.log(deepClonedPost === posts); // false
deepClonedPost.post.title = "Updated Post";
deepClonedPost.post.body.p = "Updated Body";
console.log("deepClonedPost", deepClonedPost);
console.log("Post", posts);
console.log("Post Body", posts.post.body.p); // just body
console.log("deepClonedPost Body", deepClonedPost.post.body.p); //updated body

Guilbaud

Upvotes from:

For instance, you could do something like:
 
const newPost = {
…posts.post,
title: 'Updated post',
body: {
...posts.post.body,
p: 'new Body',
}
};

If you wanna answer this question please Login or Register