'[Service Worker]: How to retry post request if api call fail due to server down?

I want to retry the POST API call when the previous API request failed due to an API down or internet failure. I used setInterval to achieve that feature. But the issue I'm facing is, the setInternal timer stops if the user force stop the chrome completely.

In this case, I want to automatically start the retry whenever the browser opens again. How to achieve that. I tried using periodic sync, but that's working only if I install the app. Without installing the app, how to retry the API call? Is there any event available in service worker to listen for the browser open?

I tried to achieve it using the periodicSync event. But in order to use that feature, users need to install our web app. So is there any other feature available like sync that I can use without installing the app itself to achieve the desired behaviour?

self.addEventListener('sync', function (e) {
  if (e.tag === SYNC_USERS) return handleSyncUsers();
});

async function handleSyncUsers() {
  const syncResult = await syncUsers();
  const failedRequests = syncResult.filter(
    (res) => res.status === 'rejected'
  );
  
  if (failedRequests.length) {        
    return startPeriodicSync();
  } else {
    return clearPeriodicSync();
  }
}    

const startPeriodicSync = () => {
  periodicSyncTimer = setInterval(handleSyncUsers, 5000);
};

const clearPeriodicSync = () => {
  clearInterval(periodicSyncTimer);
  periodicSyncTimer = null;
};


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source