I have an array of ids, stored in ids, that I'm mapping over an async function, asyncFunc. I want to store the result of the mapping into newArr and then update state via setState. Here's my code:
useEffect(() => {
const newArr = [];
ids.map((element) => {
asyncFunc(variables).then((data) => {
newArr.push({ layer: makeLayer(data) });
});
});
setState([...layers, ...newArr]);
}, [variables]);
My issue is that the state is updating before the mapping completes. How can I use .then() to update the state only when data from all the mappings were returned? Wrapping ids.map with Promise.all didn't work. In addition, the following returns an error:
useEffect(() => {
const newArr = [];
(ids.map((element) => {
asyncFunc(variables).then((data) => {
newArr.push({ layer: makeLayer(data) });
});
})).then(()=> {
setState([...layers, ...newArr]);
})
}, [variables]);
CodePudding user response:
Declare a async function to populate the array and return your array within a Promise.all. Something like this should work for what you're trying to accomplish:
useEffect(() => {
const populateArray = async () => {
const newArr = await Promise.all(ids.map(async element => {
const data = await asyncFunc(variables)
return { layer: makeLayer(data) }
})
setState([...layers, ...newArr]);
}
populateArray()
}, [variables]);
