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]);