So I googled a bit and I found that async function return promise which result value can be accessed by using.then() after this async function. That is why it can't render properly. My question is: how can I render an actual value from this promise inside.map?
const storageRef = firebase.storage().ref("/assets")
const [productList, setProductList] = useState([])
useEffect(() => {
Axios.get("http://localhost:3001/product/get").then((response) => {
setProductList(response.data)
})
}, [])
const getImage = async (bannerImage) => {
const url = await storageRef.child(bannerImage).getDownloadURL();
return url;
}
Map function (returns Error: Objects are not valid as a React child (found: [object Promise])
):
{productList.map((val) => {
return (
<div key={val.id} className="product">
<div className="item">
<h1>Product title: {val.title}</h1>
<h2>Price: {val.price}</h2>
<h2>Quantity: {val.quantity}</h2>
<h2>IMG: {getImage(val.bannerImage)}</h2>
</div>
</div>
)
})}
So, as @Chris-G suggested, you could map over response.data
in the .then
chained on Axios.get
to go ahead, get the image URLs, and construct the objects that you'll need for the render. Example:
const storageRef = firebase.storage().ref("/assets");
const getImage = async (bannerImage) => {
const url = await storageRef.child(bannerImage).getDownloadURL();
return url;
}
const [productList, setProductList] = useState([])
useEffect(() => {
Axios.get("http://localhost:3001/product/get").then((response) => {
Promise.all(response.data.map(async (rawProduct) => {
const renderReadyProduct = {
title: rawProduct.title,
price: rawProduct.price,
quantity: rawProduct.quantity
};
renderReadyProduct.img = await getImage(rawProduct.bannerImage);
return renderReadyProduct;
})).then((newProductList) => setProductList(newProductList));
});
}, [])
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.