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!
.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])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With