Caching and fetching data in PWA

mtee

Margaret W.N

Posted on September 21, 2020

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

πŸ’– πŸ’ͺ πŸ™… 🚩
mtee
Margaret W.N

Posted on September 21, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

Day 23 of 100DaysOfCode
javascript Day 23 of 100DaysOfCode

October 3, 2024

Day21 of 100DaysOfCode
javascript Day21 of 100DaysOfCode

August 22, 2024

Day22 of 100DaysOfCode
javascript Day22 of 100DaysOfCode

September 7, 2024

Day 2 of #100daysofMiva Coding Challenge
100daysofmiva Day 2 of #100daysofMiva Coding Challenge

August 22, 2024