skip to Main Content

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


  1. try using:

    setMyMovies(myMovies => [...myMovies, r])
    

    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.

    Login or Signup to reply.
  2. You have not created a new array in setMyMovies state. Try changing

    setMyMovies(newMyMovies); 
    

    to

    setMyMovies([...newMyMovies]);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search