I tried a lot of different solutions and none worked. The problem is that I'm calling a function inside useEffect, the function is working well, the variable is getting the result I want but when I'm going to set the state, nothing happens but the state update and I can see in react tools extension.
This is my code, I'm receiving as props cart that is a array of objects [{id, quantity}]
fetchDetail is a simple function that calls an api and It's working
I saw some answers saying that the useEffect does not recognize the update so I't don't rerender but I don't know why.
const [items, setItems] = React.useState([]);
async function mapIds() {
const result = [];
await Promise.all(
cart.map((product) => {
fetchDetail(product.id).then((data) =>
result.push({
id: data.id,
title: data.title,
quantity: product.quantity,
thumbnail: data.thumbnail,
price: data.price,
})
);
})
);
setItems(result);
}
React.useEffect(() => {
mapIds();
}, [cart]);
return (
<>
<section id="cart-container">
<h1>Carrinho de compras</h1>
{items.length > 0 ? (
items.map((item) => (
<div>
<p key={item.id}>{item.title}</p>
</div>
))
) : (
<p>Carrinho vazio</p>
)}
</section>
</>
);
}
Please help,
Thank you!
The promises aren't being awaited because Promise.all
isn't seeing them:
cart.map((product) => {
// This callback to .map() doesn't return anything
fetchDetail(product.id).then((data) =>
//...
)
});
The callback to .map()
needs to return the Promise
:
cart.map((product) => {
// return the Promise...
return fetchDetail(product.id).then((data) =>
//...
)
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.