问题
I have
const [data, setData] = useState([]);
const getData = async () => {
const { data } = await axios.get('/getData');
setData(data.payload);
};
and a button to call handleDelete from the backend
const handleDelete = async () => {
checked.forEach(async (element) => {
await axios.delete('/deleteData', {
data: { data: element },
});
});
await getData();
console.log(data);
};
The data is deleted from the backend, I have components that depends on data in React and for some reason, data is not being updated. The component is not updating with the new values.
Does anyone know what I might doing wrong? Any help is greatly appreciated.
回答1:
Try using async iterators for your request and see if it works.
You could read about async iterators in details here
const handleDelete = async () => {
for await (const element of checked) {
await axios.delete('/deleteData', {
data: { data: element },
});
}
await getData();
console.log(data);
};
回答2:
Thanks to zero298 for answering this question. It was due to the forEach loop firing the await call and not waiting. I changed to for..of and it's now working!
来源:https://stackoverflow.com/questions/63828489/async-await-not-behaving-as-expected-in-reactjs