Cache JSON Data in a React PWA with Workbox, and Display it while Offline

Chris Achard
InstructorChris Achard
Share this video with your friends

Social Share Links

Send Tweet

We can view the PWA offline because we are caching the static and CDN assets for the app - but the list of todo items won't display, because those API calls are not being cached. We'll add another route to the service worker, to store the result of any .json API call from our server. Then, we'll be able to view the app with the entire list of items offline.

Instructor: [00:00] In the sw.js file, let's register another route, this time for any JSON network call from our back-end server. We'll pick a network-first cache strategy, which will always try to hit the network first and only reach into the cache if it can't get to the server or the network.

[00:22] This is important for things like API calls, where we always want to have the very latest information. Then we can build and serve that and reload in Chrome with the network tab open. If we go off-line now and reload, the list works.

[00:43] We can see that network request tried but failed first. Then it went to the old cached results from the service worker.

[00:52] Back in the service worker file, we matched the entire local host URL. But in production, that might be /*.json, for example, depending on how we call it from our application.