How to handle AJAX response with service worker (Workbox) when connection is restored

828 views Asked by At

I'm building a PWA using the Vue CLI 3 PWA plugin, and I'm not sure how to handle the response from an AJAX call made while offline.

All I have is basically sample code from the Workbox documentation...

// service-worker.js
const queue = new workbox.backgroundSync.Queue('CR_OfflineQueue')
self.addEventListener('fetch', (event) => {
  const promiseChain = fetch(event.request.clone())
    .catch((err) => {
      console.log('Queued Event:', event.request)
      return queue.addRequest(event.request)
    })
  event.waitUntil(promiseChain)
})

The AJAX is just a basic Axios get() that's called when the store is loaded and in a test mutation

// store.js
getUsername () {
    return axios.get(
        'http://localhost:8005/username/',
        {
            responseType: 'json',
            withCredentials: true
        })
}

const store = new Vuex.Store({
    state: {
        username: null
    },
    mutations: {
        test_api (state) {
            getUsername()
            .then((res) => {
                state.username = res.username
            })
            .catch((err) => {
                console.error('getUsername:', err)
            })
        }
    }
})

The request is being successfully replayed, but I have no idea what to do with it, and I'm unable to find an example using workbox.backgroundSync.Queue.

As far as getUsername() is concerned, the request failed, but how do I have the calling function essentially pick up where it left off?

I don't think that need something to check the queue for the request at a regular interval to "manually" re-trigger (not via the auto replay). How would I use the queue class to take the result from the replayed request and set the username property?

0

There are 0 answers