Convert react based api call to retry based api call

Viewed 17

I have a react front end with TS which is interacting with a node backend to perform CRUD operation. Front end UI is written without any retry/fetch mechanism and fails occasionally if the api is not available.

I want to convert existing api call to retry-fetch construct.

This is the existing call from end to \api.

// existing pull data
// api.get.data(...) returns a Promise<boolean>
export const pullData = {  
  getMyData: async (x: MyType): Promise<boolean> => api.get.data(x),
};

And changed to below: my objective is to pass existing methods to a retry wrapper.

interface VoidFunction {
  (): Promise<any>;
}

// wait
function wait(duration: number): Promise<void> {
  return new Promise((resolve) => setTimeout(resolve, duration));
}

// retry with a increasing delay
async function recursiveRetry(retries: number, callbackFn: VoidFunction): Promise<any> {
  let result: unknown;
  try {
    result = await callbackFn();
  } catch (e) {
    if (retries > 1) {
      await wait(delay);
      result = await backoff(retries - 1, callbackFn, delay * 2); // increase delay X 2
    } else {
      throw e;
    }
  }

  return result;
}

// new method wrapped by retry wrapper
export const pullData = {  
  getMyData: async (x: T): Promise<boolean> => recursiveRetry(5, api.get.data(x))
};

However, I keep on getting

Argument of type 'Promise<boolean>' is not assignable to parameter of type 'TypeData'.
  Type 'Promise<boolean>' provides no match for the signature '(): Promise<any>'.

Is there a way to solve this issue? or may be a better approach?

0 Answers
Related