0

I have an array of objects that are suposed to pass as props to a element to render a list for each object, but when I try the code only one its rendered and the others are ignored even though I've console.log them and I can see them. Here's the code:

const mainFilterQueries = ['popular', 'top_rated', 'upcoming']
    const sortByMovies = "movie"
    const [moviesLists, setMoviesLists] = useState([])
    
    
    useEffect(()=>{
        createLists(mainFilterQueries, sortByMovies , setMoviesLists, moviesLists)
        console.log(moviesLists)
    }, [])

    
    async function fetchData(query, sort, setMethod, state){

        let listsCreated = []

        try {
            const response = await fetch(`https://api.themoviedb.org/3/${sort}/${query}?api_key=${apikey}`)
            const data = await response.json();
            let dataObject = {key:`${sort}-${query}`, data:data.results, title:`${query}`}
            console.log(dataObject)
            listsCreated.push(dataObject);
            setMethod([...state, dataObject])

        } catch (error) {
            console.error(error)
        }
    }
    function createLists(arr, sort, target, state){
        arr.forEach(query =>{
            fetchData(query, sort, target, state)
        })
    }
    


    

    


    return (
        <React.Fragment>
            {moviesLists.map(list =>{
            return(
                <div>
                    <MoviesList dataList={list}/>
                </div>
            )  
            })}
        </React.Fragment>
    )
Jesus Esis
  • 15
  • 3
  • You can try minimize the code to locate where the problem is. For instance, remove everything except `return`, try to use hardcoded values, add `moviesLists.length` to the outputs. Like this: `return
    {moviesLists.length} {moviesLists.map((x, i) => {i})}
    `. After this it would be much more easy to figure out what is wrong.
    – hopeless-programmer Apr 25 '21 at 02:50

1 Answers1

0

You're calling setMethod([...state, dataObject]) in a loop. state will never be updated until the next render, meaning you're actually calling the function as if it were like this: setMethod([...[], dataObject]) for every iteration.

Instead use the functional update form of setState like this:

setMethod((prev) => ([...prev, dataObject]))

The functional update ensures that the previous state is most up-to-date with any previous calls to setMethod.

See also why-calling-react-setstate-method-doesnt-mutate-the-state-immediately.

Brian Thompson
  • 13,263
  • 4
  • 23
  • 43