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:
- public/sw.js // This file installs service worker
- 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:
- What works:
After switching to offline, when I refresh my home page, everything looks good. All the links to other pages are working fine.
- What does not work:
After switching to offline, when I refresh my details page, I get this page:
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?
