Why does mosh clone object from an movies array?

Course : Composing Components
#22-Solution-Like Component
Timeline: 9:12

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?

Thank you!

movies[index].like = !movies[index].like;

This line is simply inverting the value of like (changing true to false, and versa). It doesn’t clone anything.

1 Like

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.

1 Like

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. :slightly_smiling_face:

Missed the line of code which I wanted to ask but thanks for the help. I learnt from @maverick.