Fetch cached data Vue CLI Vuex PWA

Asked by At

How do I get my cached data from service worker in to the vuex store in offline mode?

The app works in offline mode in the browser, but when I add the site to home screen with the manifest.json file included, it won't show the cached data and only the general js, css and html.

I'm having a hard time figuring out, how I get my cached data from my PWA. I already have the data cached. The problem is retrieving it back to the vuex store state called "games", to display when the app is offline.

enter image description here

The vue.config.js code for caching the api call for the service worker.

module.exports = {
  pwa: {
    workboxPluginMode: "GenerateSW",
    workboxOptions: {
      navigateFallback: "/index.html",
      runtimeCaching: [{
        urlPattern: new RegExp('API_URL'),
        handler: 'networkFirst',
        options: {
          networkTimeoutSeconds: 20,
          cacheName: 'api-cache',
          cacheableResponse: {
            statuses: [0, 200],


As you can see in the image above the code, it has stored the cache "api-cache" with the objects from the API.

Now I want to use this data in the cache from api-cache on my site, when the site is offline.

So my question is: How do I get my cached data from service worker in to the vuex store in offline mode, when a user has added the app to their home screen?

1 Answers

Ohgodwhy On

You're thinking about this in the wrong way. You don't need the service worker to do anything for you. It's already doing it by providing you with a cache implementation. Instead, you need to use the navigator.onLine hook to determine if they have internet access. If not, then hydrate your store from the cache and make sure to subscribe to any mutations and push the state back into the cache, like this:

if (!navigator.onLine) {
    const state = hydrateFromCache()

    store.subscribe((mutation, state) => cache.setItems(state)

Where the hydrateFromCache method simply pulls the store in from the cache and hydrates the state of all vuex modules.