function handleLike(movie) {
const movies = [...movies];
const index = movies.indexOf(movie);
movies[index].like = !movies[index].like; <--- Why clone this object?
setMovies(movies);
}
I understand the point of cloning first before updating the state but I couldn’t understand why he also cloned that specific object(movies[index].like = !movies[index].like;) from the movies array because when I run the code without cloning that object in the movies array it works just fine. What am I missing here?
sufian.babri has explained clearly already but I would like to add my explanation as well.
Here is what’s going on:
You can’t use assignment operator to clone objects and arrays (in most programming languages). So, if you use spread operator (…var), you will be able to clone objects easily.
const movies = [...movies]; // movies from state object is cloned into local movies variable
// get the index of the argument which is a movie object.
const index = movies.indexOf(movie);
movies[index] = {...movies[index]}; // this step was missing. Thanks @SAM. Objects are always assigned by reference so the movie objects inside the cloned array are still pointing to original movie objects.
// this is the line where you got confused:
// value of like is boolean: true means the movie is liked and false means not liked.
// to achieve this, you will need to check if the current value is true or false and based on that you can update that property.
// so, following is bit lengthy code to achieve that.
if( movies[index].like ) {
// we will get here only if the movie is liked initially.
movies[index].like = false;
} else {
movies[index].like = true;
}
// Note: you can remove above curly braces to make it more clean.
// Mosh refactored above if .. else block to toggle the value of like in single line.
movies[index].like = ! movies[index].like;
......
This is as comprehensive as it gets.
Hope this helps.
My mistake. I forgot to add the 3rd line of code where I was confused with not where you reverse like. Thanks for explaining the entire line of code. Third line was where I wanted explanation. Appreciate your help.