I would like to update a state each time I receive a promise, in a loop. But my state only shows the last promise. I guess it's because, as the set state is asynchronous, it uses the Map available before the previous state updates. How can I achieve that without using a Promise.all?
const [dataList, setDataList] = useRef(new Map())
useEffect(() => {
ids.forEach(id => {
getData(id).then(data => {
if (data) {
setDataList(dataList.set(id, data))
}
})
})
}, [ids])
CodePudding user response:
It is related to how react works. It wait for all setState and pick the last one. If you wanna avoid this behaviour use an updater function like so :
const [dataList, setDataList] = useRef(new Map())
useEffect(() => {
ids.forEach(id => {
getData(id).then(data => {
if (data) {
setDataList(dataList => {
let newDataList = new Map(dataList);
newDataList.set(id, data);
return newDataList;
})
}
})
})
}, [ids])
CodePudding user response:
I think you can achieve it with async await this way:
useEffect(() => {
ids.forEach(id => {
async function fetchMyAPI() {
const data = await getData(id);
if (data) {
setDataList(dataList.set(id, data))
}
}
fetchMyAPI()
})
}, [ids])
