React - what is the proper way to reload after multiple axios requests are done

Viewed 130

I am wondering what is the best way to make multiple axios requests, and reload the page after it's completed.

If using the way below, the page will reload before all the axios requests completed

const handleDeletePost= async (postId) => {
      //delete multiple posts
      let postToBeDeleted = selectedPostId; // it's an array containing the id of selected posts
 
      if (postToBeDeleted.length > 0) {
        postToBeDeleted.forEach(async (id) => {
          const response = await PostService.deletePost(id);
          console.log(response);
        });
        window.location.reload(); // if I put it here, the page will reload before the delete completes
      }

};
2 Answers

You can use Promise.all to parallelly fetching requests without waiting for each one to be finished:

Also, need to wait for it to be completed first, then reload the page.

const handleDeletePost = async (postId) => {
  const postToBeDeleted = selectedPostId;

  if (postToBeDeleted.length > 0) {
    const promises = [];
    postToBeDeleted.forEach((id) => {
      promises.push(PostService.deletePost(id));
    });
    await Promise.all(promises).then((values) => {
      console.log(values);
    });
    window.location.reload();
  }
};

The problem seems to be because you're expecting forEach to wait on every iteration. However, forEach and async functions do not play well together. You need to use something like Promise.all instead.

Related