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>
);
};