Service Worker Updater - React Hook & HOC
This package provides React hook and HOC to check for service worker updates.
Why would I need that?
If you use service worker in your app and would like to provide nice new update button/notification, it's perfect for you. Service Worker Updater will periodically check for new service worker. If found one, hasUpdate prop is set to true (now you can show something to your users) and use updateHandler() to activate new SW.
Service Workers are self updating by default (when user reopens your app or after some time - depending on browser). When users aren't often reloading the app, they will have old app version. Service Worker Updater = solution for that.
Installation
$ yarn add service-worker-usage
Usage
Use updater with React Hook
const hasUpdate updateHandler =
Example:
const CHECK_INTERVAL = 30 * 60 * 1000 // 30 minutesconst UPDATE_ON_NAVIGATE = true // trigger update when changing route/window.location { const hasUpdate updateHandler = if !hasUpdate return null return <button onClick= { } > Update app </button> }
Use updater as HOC (Higher Order Component)
WrappedComponent options
Example:
{ if !hasUpdate return null return <button className='updateButton' onClick= { } > Update app </button> } const CHECK_INTERVAL = 30 * 60 * 1000 // 30 minutesconst UPDATE_ON_NAVIGATE = true // trigger update when changing route/window.location UpdateButton checkInterval: CHECK_INTERVAL updateOnLoad: UPDATE_ON_NAVIGATE UpdateButtonpropTypes = hasUpdate: PropTypesbooleanisRequired updateHandler: PropTypesfunc
Do I need to modify my service worker?
Yeah, probably. This package was tested with Gatsby and gatsby-offline-plugin
, which uses Workbox behind the scenes. To activate new SW, it must trigger self.skipWaiting()
event.
If you use custom Service Worker, add message event listener to it and handle 'SKIP_WAITING' event:
self
Options
There are only two options:
-
checkInterval (int) - time in milliseconds how often check for Service Worker updates. Default: 3600000 (1h)
-
updateOnLoad (bool) - activate new service worker on route change? Default: true
How to use it in Gatsby.js?
WIP
Resources
I definitely recommend reading more about Service Workers lifecycles and their possible states: