Paula
Paula

Reputation: 61

How can I cache data from API to Cache Storage in React PWA?

I built a Progressive Web App with ReactJS and have an issue. I am using mockApi to fetch the data. When offline, my app doesn't work since the service worker only caches static assets.

How can I save HTTP GET calls from mockApi into the cache storage?

Upvotes: 5

Views: 4646

Answers (1)

Francesco
Francesco

Reputation: 10820

Along with your static assets, you can define which URLs do you want to cache:

var CACHE_NAME = 'my-cache_name';
var targetsToCache = [
  '/styles/myStyles.scss',
  'www.stackoverflow.com/'
];

self.addEventListener('install', function(event) {
  event.waitUntil(
    caches.open(CACHE_NAME)
      .then(function(cache) {
        return cache.addAll(targetsToCache);
      })
  );
});

Then you have to instruct your service worker to intercept the network requests and see if there is a match with the addresses in the targetsToCache:

self.addEventListener('fetch', function(event) {
    event.respondWith(
        caches.match(event.request).then(function(response) {

         // This returns the previously cached response 
         // or fetch a new once if not already in the cache
            return response || fetch(event.request);
        })
    );
});

I wrote a series of articles about Progressive Web Apps if you are interested in learning more about it.

Upvotes: 6

Related Questions