Our great sponsors
-
react-workbox-tutorial
a brief tutorial covering the basics of using create-react-app with Workbox, including: updating service worker and refresh, caching GET requests, and background sync.
-
ServiceWorkerUpdateListener
The ServiceWorkerUpdateListener interface extends the Service Worker API by providing a convenient way to receive update events when ServiceWorkerRegistration acquires new service workers.
-
SurveyJS
Open-Source JSON Form Builder to Create Dynamic Forms Right in Your App. With SurveyJS form UI libraries, you can build and style forms in a fully-integrated drag & drop form builder, render them in your JS app, and store form submission data in any backend, inc. PHP, ASP.NET Core, and Node.js.
-
InfluxDB
Power Real-Time Data Analytics at Scale. Get real-time insights from all types of time series data with InfluxDB. Ingest, query, and analyze billions of data points in real-time with unbounded cardinality.
git clone https://github.com/noconsulate/react-workbox-tutorial.git
To start, it might be worth your while to study this post. You can continue without it but it's probably where I learned the most about this stuff. Buried in the comments someone posted this bit of JavaScript, which does for us everything we need. We're going to use a barely-modified version of Mark's ServiceWorkerUpdateListener.js:
We're making simple app that lets you add numbers to an array. Since we're going to cache and sync database calls we'll need a database. I've chosen Supabase because it's free and easy and a good alternative to Firebase.
There are many approaches to handling requests with a service worker but the easiest way is Google's Workbox and the easiest way to get Workbox into a React app is to just use the PWA template that create-react-app provides. I was able to make an existing React app into a PWA simply by copying /src into a freshly spun CRA PWA-template but you can also get your bundle into Workbox other ways. It's just trickier.
Chrome has a handy tool called Lighthouse baked right into DevTools. So navigate to http://localhost:5000 in Chrome using an incognito tab, open up DevTools, and find the Lighthouse tab. Click on 'Generate report', wait several seconds, and voila!