How do I make synchronous calls in react js

72 Views Asked by At

I am beginner to react js and I am working on a small feature to reset table data in one of our UI projects.

Current functionality:

  • There is a save button which saves all the overrides(i.e., saves changes made to the original table data for this id in another table called overrides table) in the DB and
  • a reset button to clear these saved overrides(i.e., deletes the overrides data from the overrides table for this id ).
  • Once the user clicks on Reset button on the UI, the current code does an api call to the backend to clear all the overrides in the table data.
  • And the users have to refresh the page to see the up-to date data.

Current code:

const handleClearData = () => {
    clearData({})
  }

The new requirement is to refresh the data after clearing the overrides in the table i.e., I have to call the refetchData call after doing a reset. something like below:

const handleClearData = () => {
    clearData({})
    refetchData()
  }

clearData uses a common function(code below) which is a Async call. And refetchData also uses a similar common function as below.

function fetchResponse (url, fetchOptions) {
  const fetchFailureResponse = error => {
    return Promise.reject(
      Error(`${error.message}`)
    );
  };


  return fetchMethod(url, fetchOptions)
    .then(parseSuccessResponse)
    .catch(fetchFailureResponse)
    .then(parseResponse => {
      // code to parse the error response
      return Promise.reject(error);
    });
}

when I hit the reset button, I can see that sometimes the refetchData call is made even before the clearData call, so even though my table overrides are deleted, the refreshed data(from the refetchData call) is stale and my table on the UI doesn't reflect the new data.

I need to ensure that I have to call the refetchData once the clearData call is completed. I tried adding a timeout but 1/2 seconds timeout isn't helpful and a timeout more than that is weird(i.e., it takes 5 seconds for the data to get refreshed after making the reset which is spoiling the user experience).

Can I please get some help on how to achieve this? Been stuck on this for quite sometime.

Edit: clearData does a delete api call which is internally using the fetchResponse method. refetchData is a get api call which is also using the fetchResponse method.

1

There are 1 best solutions below

2
danielRICADO On

async

assuming clearData is returning a Promise.

clearData({}).then(() => refetchData())

checkout async await if you want clearer syntax

async function handlecleardata() {
   await clearData({})
   await refetchData()
}