DEV Community

Margaret W.N
Margaret W.N

Posted on

8 1

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

SurveyJS custom survey software

JavaScript UI Libraries for Surveys and Forms

SurveyJS lets you build a JSON-based form management system that integrates with any backend, giving you full control over your data and no user limits. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more.

Learn more

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay