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.