I’m trying to make a reaction to the change. I have a State variable that stores an array of elements. When I click on the button, there is a request to the api. According to the answer, I change the state variable. When I use the post method, for some reason my useEFfect does not write anything to the console. when I use the delete method, everything works as I expected. Where is my mistake?
useEffect(() => { console.log(myMovies) }, [myMovies]);
function handleMovietoggleLike(movie, metod) {
if (metod === 'POST') {
mainApi.postMovies(movie)
.then((r) => {
const newMyMovies = myMovies;
newMyMovies.push(r);
setMyMovies(newMyMovies);
})
.catch((err) => console.log(err))
.finally(() => {
return
})
}
if (metod === 'DELETE') {
mainApi.deleteMoviesId(movie._id)
.then((r) => {
const newMyMovies = myMovies.filter(m => m._id !== movie._id);
setMyMovies(newMyMovies);
})
.catch((err) => console.log(err))
}
return;
}
I expected that the my Movies variable would change by setMyMovies. useEffect with the my Movies dependency would write to the console after each call to my handleMovietoggleLike function. But this happens only with the call of this function with the value of the delete method
2
Answers
try using:
Essentially you are not appropriately copying the original array for React. React is immutable and practically forces you to do immutability because they need a new value in order to re-render. Although your code is technically correct, it will not force the re-render and thus the triggering of the hook appropriately.
You have not created a new array in setMyMovies state. Try changing
to