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
Published 5 years ago
Updated 5 years ago

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.

egghead
egghead
~ just now

Member comments are a way for members to communicate, interact, and ask questions about a lesson.

The instructor or someone from the community might respond to your question Here are a few basic guidelines to commenting on egghead.io

Be on-Topic

Comments are for discussing a lesson. If you're having a general issue with the website functionality, please contact us at support@egghead.io.

Avoid meta-discussion

  • This was great!
  • This was horrible!
  • I didn't like this because it didn't match my skill level.
  • +1 It will likely be deleted as spam.

Code Problems?

Should be accompanied by code! Codesandbox or Stackblitz provide a way to share code and discuss it in context

Details and Context

Vague question? Vague answer. Any details and context you can provide will lure more interesting answers!

Markdown supported.
Become a member to join the discussionEnroll Today