DEV Community 👩‍💻👨‍💻

Margaret W.N
Margaret W.N

Posted on

Caching and fetching data in PWA

I am back with a working service worker. The article covers caching data and fetching cached data in a Progressive Web App, which were today's lessons.

To cache data you have to declare two variables, one holds the cache name and the other holds the data/files to be cached (should be an array of files).

const cacheName = 'cache-v1';
const cacheResources = [
  'index.js',
  'style.css',
]
Enter fullscreen mode Exit fullscreen mode

Caching resources/data:

self.addEventListener("install", event => {
  console.log('Service Worker install event');
  event.waitUntil(
    caches.open(cacheName)
    .then(cache => {
      console.log("Service Worker: Caching files");
      return cache.addAll(cacheResources );
    })
    .catch(err => console.log(err))
  );m
});
Enter fullscreen mode Exit fullscreen mode

Code Explained:
Self points to the global scope which in this case is the service worker. You attach an event listener which listens for the install event, opens: .open() cache storage with the declared cache name and adds all the files addAll().

Fetching data:

self.addEventListener("fetch", event => {
  console.log('Sw: fetching');
  event.respondWith(caches.match(event.request)
  .then(cachedResponse => {
    return cachedResponse || fetch(event.request)
  }))
})
Enter fullscreen mode Exit fullscreen mode

Code Explained:
To fetch data you'll listen for the fetch event and check if the requested data matches the cached data: caches.match(). If the data matches send back the data if not make a network request. This should be within respondWith() function which prevents the default browsers fetch handling.

That's it for Day 67
Let's do this again tomorrow

Top comments (0)

You’ve already scrolled down this far, why not join our community of 900k+ developers all learning together?