TotalNewb
TotalNewb

Reputation: 43

PWA - How to fetch data from API endpoint and cache it in service-worker?

I am on a service-worker.js file attempting to cache JSON data from an API endpoint for a Progressive Web App.

This creates a weather file in the cache, but the contents are my HTML page. If I console.log(data), I see the object I need.

I've tried cache.add(JSON.stringify(data)) and cache.addAll(data) to no avail.

self.addEventListener('install', event => {
  event.waitUntil(
    caches.open('weather')
      .then(function(cache) {
        fetch('/api/weathercurrent')
          .then(function(response) {
            return response.json();
          })
          .then(function(data) {
            cache.add(data);
          })
      })   
  )
});

Upvotes: 0

Views: 1809

Answers (2)

user3390456
user3390456

Reputation: 11

After a lot of hours this is easiest way:

self.addEventListener("fetch", event => {  
  event.respondWith(caches.match(event.request)  
    .then(cachedResponse => {        
      if (cachedResponse !== undefined) {
        return cachedResponse;
      } else {
        return fetch(event.request)
          .then((response) => {
            let responseClone = response.clone();
            caches.open("extraData").then((cache) => {
              cache.put(event.request, responseClone);
            });
            return response;
          })
          .catch(err => console.log(err));
      }
    })
    .catch(err => console.log(err))
  )
})

Upvotes: 1

TotalNewb
TotalNewb

Reputation: 43

The solution was more simple than I thought. I thought because the data was JSON, I needed to use request and response handlers.

event.waitUntil(
  caches.open('weathercurrent')
    .then(cache => cache.add('/api/weathercurrent'))
);

Upvotes: 1

Related Questions