I'm getting infinite loop in React useEffect and i'm totally confused

Viewed 61

I'm working with tmdb api, I've been using react's useEffect and useContext for minor stuff and it works. I decided to use the api and it has been going into this infinite loop anytime I try to run it. I'm using axios with useEffects and useContext. Below is the component calling axios

enter image description here

            function MovieList(props) {
                    useEffect(() => {
                        const getMovies = async () => { };
                      try {
                        const response = await axios.get(movieUrl, { cancelToken: source.token });
                        addMovies(response.data.results);
                        // setLoading(false)
                      } catch (error) {
                        if (axios.isCancel(error)) {
                          console.log('Request canceled', error.message);
                        } else {
                          // handle error
                          throw error
                        }
      }
                        getMovies();
                    }, []);
                
                    return (
                        <React.Fragment>
                            <div className="container-fluid pl-5">
                                <h2 className="white mt-4">{pageTitle}</h2>
                                <div className="row">
                                    {movies.map((movie) => {
                                        return <Movie key={movie.id} movie={movie} />;
                                    })}
                                </div>
                            </div>
                        </React.Fragment>
                    );
                }

My code goes into an infinite loop and it's driving me crazy.

And my context code is found below:

export const MovieProvider = (props) => {
    const [isFav, setIsFav] = useState(false)
    const [movies, setMovies] = useState([]);
    const [filtered, setFilteredMovies] = useState([])

    const addMovies = (res) => {        
        setMovies([...res]);
    }

    const addFavMovies = (res) => {     
        if(res){ 
        setMovies([...res]);
        }
    }

    const addFilteredMovies = (res) => {        
        setFilteredMovies([...filtered, res]);
    }

    return (
        <MovieContext.Provider value={{
            fav: [isFav, setIsFav],
            movies, addMovies, addFavMovies,
            filtered, addFilteredMovies,
        }}>
            {props.children}
        </MovieContext.Provider>
    )
}

0 Answers
Related