Pwa Workbox Sync-background UI

589 Views Asked by At

BackgroundSync, from workbox, works perfectly but I have a problem

I want that when I modify an element, even if the request is still in indexedDB, the element is not updated on my pwa (UI), when I am offline. For now, when I change the element ( in a simple input), the request is in my indexedDB, and if I refresh the page, it gets back as before. When I have network again, the request is sent and the element is updated in the UI

I use workbox V6 for my worker service, and a PHP API to modify my elements this is the part of my service worker for sync :

const bgSyncPlugin = new BackgroundSyncPlugin('offlineSyncQueue', {
  maxRetentionTime: 0.1 * 60 
});

registerRoute(
  /http:\/\/localhost:3001/,
  new NetworkFirst({
    plugins: [bgSyncPlugin]
  })
);

Can you help me, please

1

There are 1 best solutions below

4
On

It's difficult to modify the IndexedDB entry that workbox-background-sync creates for you to adjust the queued request based on updated parameters.

What I'd recommend instead is to directly delete the IndexedDB entries that you know are out of date when you make changes in your UI, and after those entries are deleted, trigger another HTTP request to your server. If it fails, the newest request with updated values will be queued and retried once the network comes back, and your old requests (which will you have deleted from IndexedDB) won't.

It's not very straightforward to do this, but the basic idea, if you needed to, would be something like:

// https://github.com/jakearchibald/idb for ease of use.
const {openDB} = await import('https://unpkg.com/[email protected]/build/esm/index.js?module');

const db = await openDB('workbox-background-sync');

const queuedRequests = await db.getAllFromIndex('requests', 'queueName');

for (const queuedRequest of queuedRequests) {
  // Loop through queuedRequests until you find the one you want,
  // based on some criteria in shouldDelete().
  if (shouldDelete(queuedRequests)) {
    await db.delete('requests', queuedRequest.id);
  }
}

Note that this approach makes several assumptions about the way workbox-background-sync serializes its requests to IndexedDB, and those might not always hold in future versions of Workbox.