4

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!

E.K.Garcia
  • 49
  • 2
  • 7

1 Answers1

3

.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])
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
  • I used `.then(data => console.log(data))` as one of my attempts to make this work. Thank you I won't do that again. The code is still returning undefined, and I use the Promise because I need an array of the fetches to map() over them and output some data. – E.K.Garcia Apr 23 '21 at 03:28
  • Did you try the code in my answer? You need to *both* remove the `console.log` *and* return the Promise from the `.map` callback. – CertainPerformance Apr 23 '21 at 03:32
  • You are right! I had to return the promise, that was it! Thank you:) – E.K.Garcia Apr 23 '21 at 03:49