Home > Back-end >  What is the best way to execute a function after TWO or more async functions finish in React?
What is the best way to execute a function after TWO or more async functions finish in React?

Time:02-08

I have two functions that run asynchronously getting data from the API. Both of them are called from their own useEffect().

I have a third function that needs to run once those two functions have been fully completed.

How can this be accomplished?

Edit: Both of the async functions look like this:

   useEffect(() => {
    fetchBudgetBucketsData();
  }, [fiscalYear]);

  useEffect(() => {
    fetchBudgetBucketsData();
  }, [fiscalYear]);

 const fetchBudgetsData = async () => {
    setIsFetchingBudgets(true);
    const res = await getBudgets(orgID, `${parseInt(fiscalYear)}`, '', budgetType);
    setIsFetchingBudgets(false);
    if (isErrorResponse(res)) {
      console.warn(res.details);
      message.error(res.displayText);
      return;
    }
    setBudgets(res.budgets);
  };

 const fetchBudgetBucketsData = async () => {
    setIsLoadingBudgetBuckets(true);
    if (orgID === undefined) {
      return;
    }

    const res = await getBudgetBuckets(orgID, fiscalYear);
    setIsLoadingBudgetBuckets(false);
    if (isErrorResponse(res)) {
      console.warn(res.details);
      message.error(res.displayText);
      return;
    }
    setBudgetBuckets(res.buckets);
  };

Whenever the budget data or bucket data is updated, I want to call another function that checks for errors. However when the page loads, I need it to wait for both of those functions to be finished before it checks for errors.

Edit #2:

After some debugging, it looks like the issue might have to do with when React updates the state. Since I am trying to check for errors in data saved in the state.

CodePudding user response:

One way could be chaining Promises.

Promise.all([ApiCall1, ApiCall2])
// At this point two promises above will be resolved
.then(() => ApiCall3)

Read more

CodePudding user response:

I discovered the issue was caused by how React chooses when to update the state and not how I was calling these functions asynchronously.

I was able to call my Error check function by hooking it into the output of the data fetch calls. This makes sure that the error check only runs when either the budgets or buckets are edited and finished being changed.

useEffect(() => {
    getWarningsAndErrors();
  }, [budgets, budgetBuckets]) //Update errors whenever we edit budgets or buckets
  •  Tags:  
  • Related