React - help with this toggle function

React - help with this toggle function
0

#1

I am doing this React course where we are doing a movie app, we have an object with dummy info representing the movies database.

The instructor created a toggle function to change the state of a like button. But because the function does not have an if statement, I am failing to see how this function is toggling the class. This is how the function looks like:

handleLike = (movie)  => {
    const movies = [...this.state.movies]
    const index = movies.indexOf(movie)
    movies[index] = {...movies[index]}
    // I understand everything until this point
    // How is this toggling anything?
    movies[index].liked = !movies[index].liked
    this.setState({ movies })
 
  };

To give you more context, the liked key is originally undefined in each object, you can see that here:

{this.state.movies.map(movie => (
              <tr key={movie._id}>
                <td>{movie.title}</td>
                <td>{movie.genre.name}</td>
                <td>{movie.numberInStock}</td>
                <td>{movie.dailyRentalRate}</td>
                <td>
                  <Like liked={movie.liked} onToggleClass={() => this.handleLike(movie)} />
                </td>
                <td>
                  <button onClick={() => this.handleDelete(movie)} className="btn btn-danger btn-sm">
                    Delete
                  </button>
                </td>
              </tr>
            ))}

So with the toggle function all I see is that the liked key is being set to true with the ! operator. But when I click again, how does it go back to be undefined so it can be false?

The Like component looks like this just in case you need it for more context:

const Like = (props) => {
  let classes ="btn fa fa-heart";
  if(!props.liked) classes += "-o";
  console.log(props);
  return (
    <i onClick={() => props.onToggleClass(props.movie)}
      className={classes}
      aria-hidden="true">
    </i>
  );
};

#2

Umm I think I understand now, with a much simpler example

const obj = [
	{
  	title: 'Terminator',
    liked: undefined
  }
];

document.querySelector('.btn').addEventListener('click', () => {
  console.log(obj.liked)
  obj.liked = !obj.liked
  console.log(obj)
})

Basically what’s going here is that since the value of the liked key is originally a falsy value, by using the ! operator we change the liked key to a truthy value, and then when it’s true and we click again, it turns into a falsy value again due to the ! operator, and so on and so forth.

Looks like I answered my own question. Please feel free to correct me if I’m wrong here or if I’m missing something.