3

I have registered my service worker by adding serviceWorker.register(); in my code.In create-react-app Api results are not cached.How do we cache Api result so we counld improve Offline support.

Gokul Sajan
  • 373
  • 4
  • 14

1 Answers1

1

you can cache the network responses and can be served from it as below

window.addEventListener('fetch', function(event) {
  event.respondWith(
    caches.open('your-app').then(function(cache) {
      return cache.match(event.request).then(function (response) {
        return response || fetch(event.request).then(function(response) {
          cache.put(event.request, response.clone());
          return response;
        });
      });
    })
  );
});

resource

Noushad
  • 6,063
  • 3
  • 25
  • 28
Eslam Abu Hugair
  • 1,162
  • 1
  • 11
  • 23
  • 1
    Just a note, that is a very simple, minimal example. For a real production application you will need to have a much more sophisticated solution to manage what strategy is used for different resources, data, which includes how cached assets are invalidated etc. – Chris Love Nov 05 '19 at 03:20