Home > Net >  React: how to display success message if all requests were successful in a loop
React: how to display success message if all requests were successful in a loop

Time:09-22

I have an array of items. I am iterating over all items and making a post request to create a record in the db with axios. I want to show a success message if all requests were successful. Not sure how to do it?

I'm thinking of creating an array and pushing true and false to it. if the array values do not include false, then all requests were successful.

Any suggestion?

const handleAddTaskBacklogs = () => {
  setSubmitting(true);
  openSnackbar('Adding to task backlogs...');

  try {
    selectedBacklogs.forEach(async (backlog) => {
      await createResource.mutateAsync({
        url: taskBacklogsUrls.list(),
        values: {
          task: taskId,
          backlog,
        },
      });
    });

    openSnackbar('Backlog(s) added to the task');
    refetchTaskBacklogs();
    setActiveBacklog(null);
  } catch (err) {
    console.log(err.message);
    console.log(err.response && err.response.data);
    openSnackbar('Failed to add backlog(s) to the task');
  } finally {
    setSubmitting(false);
  }
};

CodePudding user response:

You could map the selectedBacklogs to an array of Promises and Promise.all them.

The Promise.all() method takes an iterable of promises as an input, and returns a single Promise that resolves to an array of the results of the input promises. This returned promise will resolve when all of the input's promises have resolved, or if the input iterable contains no promises. It rejects immediately upon any of the input promises rejecting or non-promises throwing an error, and will reject with this first rejection message / error.

const handleAddTaskBacklogs = async () => {
  setSubmitting(true);
  openSnackbar('Adding to task backlogs...');

  try {
    const promises = selectedBacklogs.map((backlog) => {
      return createResource.mutateAsync({
        url: taskBacklogsUrls.list(),
        values: {
          task: taskId,
          backlog,
        },
      });
    });

    const result = await Promise.all(promises);

    // all successful

    openSnackbar('Backlog(s) added to the task');
    refetchTaskBacklogs();
    setActiveBacklog(null);
  } catch (err) {
    console.log(err.message);
    console.log(err.response && err.response.data);
    openSnackbar('Failed to add backlog(s) to the task');
  } finally {
    setSubmitting(false);
  }
};

Promise.all will immediately reject at the first rejection. If you still need to process all the asynchronous POST requests then you may use Promise.allSettled. You can then check the status of each to see which were fulfilled successfully.

const result = await Promise.allSettled(promises);
const allFulfilled = result.every(({ status }) => status === 'fulfilled');

if (allFulfilled) {
  // all successful
}
  • Related