Search code examples
reactjsundefineduse-effectpromise.all

Promise.all() inside useEffect in react returns an array of undefined items


It works after the fetch, then after Promise.all() returns undefined. Same happens with Promise.allSettled().

function DrinksPage(props){
    const [drinkCard, setDrinkCard] = useState([]);

    var id = props.id;
   
    useEffect( () =>{
        var drinksPromises = 
            id.map( obj => {
                var id = obj.idDrink;
                
                fetch(`https://www.thecocktaildb.com/api/json/v1/1/lookup.php?i=`+ id)
                .then(res => res.json())
                .then(data => console.log(data)) //Returns what I want
            });
               
        Promise.all(drinksPromises).then(data => {setDrinkCard(data)}) 
    },[id])
    
    console.log(drinkCard); //Returns an array of undefined values

It might be a simple issue since I'm new with react, but I have tried everything I could think of and it's still returning undefined.

Please, let me know what my mistake/s is/are, and how can I fix them. Thank you!


Solution

  • .console.log returns undefined, and Promises resolve to the value returned by the last .then in the Promise chain.

    Here:

    .then(data => console.log(data)) //Returns what I want
    

    you're taking the populated data, console.logging it, and then returning undefined, so the Promise there will resolve to undefined.

    You're also not using that Promise anywhere. You should return it from the .map callback.

    You need:

    useEffect(() => {
        const drinksPromises = id.map(obj =>
            fetch(`https://www.thecocktaildb.com/api/json/v1/1/lookup.php?i=${obj.idDrink}`)
                .then(res => res.json())
        );
        Promise.all(drinksPromises).then(data => { setDrinkCard(data) })
    }, [id])