0

I have a Json object stored in cache , Please see my cache here.

And I want to retrieve the json values from my service worker

   caches.open('my-post-request').then(function (cache) {
      cache.match('/cached-products.json').then(function (matchedResponse) {
        return fetch('/cached-products.json').then(function (response) {
          return response;

        })
      });
    });

is there a way to do that? exploring the response in the console I can just see the properties headers, ok, status, type, url, body, but I cant find my json values anywhere.

I would appreciate any suggestion.

Thanks

JC_Rambo
  • 61
  • 7

1 Answers1

0

You could try something like this:

var CACHE_NAME = 'dependencies-cache';

self.addEventListener('install', function(event) {

console.log('[install] Kicking off service worker registration!');

event.waitUntil(
    caches.open(CACHE_NAME).then(function(cache) { //  With the cache opened, load a JSON file containing an array of files to be cached

      return fetch('files-to-cache.json').then(function(response) {
         return response.json(); // Once the contents are loaded, convert the raw text to a JavaScript object

            }).then(function(files) {
              console.log('[install] Adding files from JSON file: ', files); // this will log the cached json file 

                 return cache.addAll(files); // Use cache.addAll just as you would a hardcoded array of items

       });
    })
  .then(function() {
      console.log(
      '[install] All required resources have been cached;',
      'the Service Worker was successfully installed!'
      );
   return self.skipWaiting(); // Force activation   
      })
    );
 });

This will solve your problem. From the code above, you can simply return your response as response.json() to convert the raw text to a Javascript Object. For full implementation of Service Worker to cache JSON file, you can visit this documentation.

Jessica Rodriguez
  • 2,899
  • 1
  • 12
  • 27