async await not behaving as expected in reactjs

[亡魂溺海] 提交于 2021-02-11 12:35:32

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!