I think so, yes. I’m not sure about performance though. Could you compare both approaches with - say - 10000 movies trying to toggle the first movie in one run and the last in another?
const movies = this.state.movies.map(m => {
return m._id === movie._id ? {m.liked: !m.liked } : m;
});
do not need to copy m inside map function. because map funtion is a funcional programming style, it copied array for your already.
in this case, it should be fine.
however in real project programming you need to check the object and the object’s property you use is empty or not all the time. Because the movies’ data is coming from the server end. It is not reliable.
I will code this way:
import _ from “lodash”;
const movies = .cloneDeep(this.state.movie) || [];
const index = movies.indexOf(movie);
if(.isEmpty(movies[index]) && _.isEmpty(movies[index].liked){
movies[index].liked = !movies[index].liked;
}
I’m not sure if it’s not a good idea to deepClone() members of a React state. Wouldn’t React think every single movie was changed and perform unnecessary rerenders, at least in vDOM? And besides that deep clones can be far more expensive than shallow copies.