0

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.

Bill
  • 512
  • 4
  • 14
  • 1
    It _might_ have something to do with how you are using the `.forEach()`. The data is probably deleted from the backend correctly, but not before you make the request to actually go and get the data. `getData` won't wait for the `forEach` to finish before firing. See this question: https://stackoverflow.com/questions/37576685/using-async-await-with-a-foreach-loop – zero298 Sep 10 '20 at 11:15
  • 1
    Does this answer your question? [Using async/await with a forEach loop](https://stackoverflow.com/questions/37576685/using-async-await-with-a-foreach-loop) – zero298 Sep 10 '20 at 11:15
  • @zero298 Thank you so much! That was it! I didn't know foreach doesn't wait. Learn something new everyday! – Bill Sep 10 '20 at 13:40

2 Answers2

0

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);
  };
Prateek Thapa
  • 4,829
  • 1
  • 9
  • 23
0

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!

Bill
  • 512
  • 4
  • 14