0

I am trying to get data from an api, The Movie Database, for which I am using React (version 18) and axios (version 0.27.2). The question is that when I take the data, and the setState is done. starts an infinite loop that doesn't end. I share code for better understanding.

import { useEffect, useState } from "react"
import { useNavigate } from "react-router-dom"
import axios from 'axios'


function Listado() {

    const [movieList, setMovieList] = useState([])

    const navigate = useNavigate()

    useEffect(() => {

        const token = localStorage.getItem('token')

        console.log(token)
        if (token == null) {
            navigate('/')
        }
    }, [navigate])

   
    useEffect(() => {

        const api = 'b34999ac538aed71a19355d996f1081f'
        const options = {
            method: 'GET'
        }

        const rest = (async () => {
            await axios(`https://api.themoviedb.org/3/discover/movie?api_key=${api}&language=es-ES&page=1p`, options)
                .then(response => {
                    setMovieList(response.data.results)
                    console.log(movieList)
                })
        })

        rest()

    }, [movieList])
   

    return (
        <>
            
            <div className='col3' style={{ border: '1px solid red' }}>Peli 1</div>

        </>)
}
export default Listado

The result it gives is the following in the console:

(twenty) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {… }, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]

Line that does not stop repeating itself infinitely. I hope there is someone who can shed light on this problem that I don't know how to solve. Greetings and thanks.

  • How many times were you expecting to call the API? Once, on mount, or what? Sounds like you just need to change to an empty dependency array – CertainPerformance Jul 03 '22 at 21:45
  • Once, I already tried with an empty dependency array and the result it returns is an empty array. If I delete the dependency array, it returns the same result multiple times. – Jose Antonio Miro Erdmann Jul 03 '22 at 21:47

0 Answers0