I have an array with ids like [123,345,212,232.....] I have a Rest API that responds the particular product with respect to an id .
So in ReactJS, how would I loop through the array and get the products and store in state
I tried doing this in useEffect{running once as in componentDidMount} but it only stores the first product in array.
Are there better ways to accomplish this?
My Actual Code that has the problem is
useEffect(() => {
const getBought = async () => {
user.bought.map(async (boughtID) => {
let bought = await get(`/bought/${boughtID}`, {}, true);
let boughtDate = bought.createdAt.slice(0, 10);
bought.products.map(async (pr) => {
let product = await get(`product/${pr.product}`);
let quantityBought = pr.quantity;
setAllBoughts({
...allBoughts,
[boughtDate]: [
...(allBoughts.boughtDate || []),
{
product,
quantityBought,
},
],
});
});
});
};
getBought();
}, []);
So I have a user which has arrays of boughtIds in bought key...
so I am looping throughout those bought keys
A bought schema has products which has product id and number of product bought (pr.product and pr.quantity).. So I am hitting the API , and save all the products in a state object.
so allBoughts is state which is an object that has keys as (dates) as in the code .createdAt.slice(0,10) which gives me date removing rest of stuffs mongodb added.
But everytime I do it, there are few things that happen.
Either only the first item is saved, and rest are not Either the same item gets overwritten or the page reloads infinitely(especially whrn I try to remove dependency array from useEffect)
I tried doing this in useEffect{running once as in componentDidMount} but it only stores the first product in array.This sounds like the right approach, it just had a bug in it. Please show us the code you wrote for this