Retrieval of stored information using Vue CLI, Vuex, and PWA

Is it possible to access cached data from a service worker in the vuex store while offline?

My app functions properly in offline mode in the browser, but when added to the home screen with the manifest.json file, it fails to display the cached data and only shows general js, css, and html.

I'm struggling to find a way to retrieve the cached data from my Progressive Web App (PWA). The data is already cached, but I can't seem to get it back into the vuex store state named "games" to show it when the app is offline.

https://i.sstatic.net/yv64x.png

The vue.config.js code snippet 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 displayed in the image above, the code has saved the cache "api-cache" containing objects from the API.

Now, I aim to utilize this cached data from api-cache on my site, specifically when the site goes offline.

Thus, my inquiry is as follows: How can I transfer cached data from the service worker to the vuex store while in offline mode, particularly after a user adds the app to their home screen?

Answer №1

Your approach needs a shift in perspective. The service worker is already handling caching for you, so there's no need to make it perform additional tasks. Instead, utilize the navigator.onLine hook to check for internet connectivity. If offline, retrieve data from the cache to hydrate your store. Make sure to subscribe to any mutations and update the cache accordingly:

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

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

The hydrateFromCache function retrieves and loads cached store data, ensuring all vuex modules are properly hydrated.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Using HTML5 canvas to draw circles with additional metadata stored in variables

I'm designing a seating chart that will indicate spots with circles and show a tooltip on mouseover with the person's first name, last name, and possibly other details. I plan to use Kinetic.JS for region/tooltip support based on the tutorials I& ...

multiples of order quantities in WooCommerce

In order to implement a minimum order quantity based on category, I came across this code. However, it seems to apply to all products in the cart. What additional modifications would be needed to specify certain categories? My objective is for customers t ...

implementing select2 and binding an event to it

I have a simple select2 setup where I am passing a common class in the options and trying to trigger a jQuery event on every change or click of an item in the dropdown. Here is my code snippet: <select name="transferfrom" id="transferfrom" data-placeho ...

Retrieve a snippet of code following the image URL on your web browser

While attempting to change the background image upon hovering, I encountered an interesting issue. The code for the image URL initially appears as follows: background-image: url('../assets/img/project1.png'); However, upon inspecting the co ...

Preventing audio from being muted using JavaScript requires the removal of audio tags through a MutationObserver

I attempted to utilize the script below to eliminate all audio from a specific website: // ==UserScript== // @name addicto // @namespace nms // @include http://* // @include https://* // @version 1 // @grant none // ==/UserScrip ...

Unable to locate module: Issue arises because 'vue-csv-import' cannot be resolved

Currently, I am in the process of importing vue-csv-import for vue 2. This was done by executing the following command: npm install [email protected] The package.json file has been updated with the following details: "dependencies": { &q ...

What is the best way to utilize a variable retrieved from a mysql connection in NodeJS within an asynchronous function?

My current project involves scraping a website using Puppeteer. I am aiming to extract the date of the last post from my database and compare it with the dates obtained during the scrape. This way, I can determine if a post is already present in the databa ...

When a div is clicked, the text inside the button changes. If another div is clicked, the previous text is reset

I am seeking a solution for changing the text of a button within three columns when a specific 'advice-card' div is clicked on. The text should change to 'Hide' for the clicked div, and the other buttons should switch back to 'Show ...

What is the method for retrieving a child element using its ID in JavaScript?

Below is the HTML code I am working with: <div id="note"> <textarea id="textid" class="textclass">Text</textarea> </div> I am trying to retrieve the textarea element without using document.getElementById("textid"). This is what I ...

AngularJS seems to have trouble with routing functionality

I've recently started learning AngularJS and have been following CodeSchool's video series. However, I've encountered an error when trying to route through a click on an image. Can someone please assist me with this? Below are my HTML and J ...

Error: Value of incoming scope in Angular Directive is not defined

When working in html, I passed an object into a directive like this: <lcd-code ldcCode="{{ detail.program.ldcCode }}"></lcd-code> The value of detail.program.ldcCode is "PSIH"... However, in the Directive, it is showing up as undefined: var ...

Is it possible to simultaneously verify if an array is empty within an Object along with checking the other fields?

Let's say I have an object that has the following structure: filter: { masterName: '', service:[], } What is the best way to determine if both the array and masterName field are empty? ...

Utilizing Ajax and jQuery to extract information from an XML file based on an identification number

Currently, I am looking for a way to showcase a specific product with its description from my XML file by using the product's ID. The structure of my XML file is shown below: https://i.sstatic.net/wFWgW.png Below is the JavaScript code I am using: ...

Expanding the size of the number input in Twitter Bootstrap to accommodate changing content dimensions

I have a numeric input field that I want to customize in terms of width. I need the field to start with a minimum width so that -1, the default value, fits nicely inside. As the value changes, whether decreasing to -100 or increasing to -1,000 and beyond ...

Attempting to refresh the choices in a dropdown list by sending a request via jQuery leads to specific

I have a Dropdown on my View that looks like this... <div class="editor-field"> @Html.DropDownListFor(model => model.CategoryId, new SelectList(new List<string>(), ""), "Select ...") </div> Within my controller, there is an action ...

Trigger $q manually in AngularJS

My understanding of $q in AngularJS is that it runs every time I refresh my page, similar to using a function in ng-init. Here is the code for $q.all that I have: $q.all([$scope.getCart(), $scope.getCategory(), $scope.getMenu(), $scope.getRestaurant()]). ...

NodeJS Express REST API fails to fetch data in GET request

As I work on developing a REST API using NodeJS and Express, I have set up routes for handling "offers". However, when attempting to send a GET request, I receive an empty response along with a 200 status code. Here is the snippet from routes.js: route ...

Incorporate information into a JSON structure within SAPUI5

While diving into SAPUI5, I decided to challenge myself by creating a basic form. Unfortunately, my attempts are falling short as the new entry I'm trying to add to my JSON model isn't showing up in the file when I run my code. No error messages ...

Populating a form field using another input

I am facing an issue with retrieving the price of a product in one field when the product name is selected in another field on a simple POS system. It works fine for the first product, but when I add another row for the next product, the price does not dis ...

Canceling the http post request while subscribing to a service

After wrestling with this issue for a whole week, I am still unable to successfully send a basic post request to the Heroku server using Angular HttpClient. I've meticulously defined all the services in the provider section of the main app module. Str ...