How to add dynamic routes to cache when installing service worker?

Viewed 308

I have completed creating my webapp using React.js. Now, I am trying to make it work offline.

My application has 2 routes defined:

/: Home page

/:id: Details page

I have already cached the API calls by using react-query.

Now, I just need to cache all of my static files and routes.

For that I have created 2 files:

  1. public/sw.js // This file installs service worker
  2. src/swDev.js // This file registers service worker

Code:

src/swDev.js

const swDev = async () => {
  let swUrl = `${process.env.PUBLIC_URL}/sw.js`;
  const response = await navigator.serviceWorker.register(swUrl);
  console.log(response);
}

export default swDev;

public/sw.js

let CACHE_NAME = 'appV1';

this.addEventListener('install', (event) => {
  event.waitUntil(
    caches.open(CACHE_NAME).then((cache) => {
      cache.addAll([
        '/static/js/main.chunk.js',
        '/static/js/0.chunk.js',
        '/static/js/bundle.js',
        '/index.html',
        '/',
      ]);
    }),
  );
});

this.addEventListener('fetch', (event) => {
  if (!navigator.onLine) {
    event.respondWith(
      caches.match(event.request).then((response) => {
        return response;
      }),
    );
  }
});

Now when I run my app and make it offline:

  1. What works:

After switching to offline, when I refresh my home page, everything looks good. All the links to other pages are working fine.

  1. What does not work:

After switching to offline, when I refresh my details page, I get this page:

enter image description here

I know that I have not added details route to cache, when I install the service worker. But my Details page is a dynamic route. Can someone tell me, what should I add for that dynamic route to be cached?

0 Answers
Related