How to implement skipWaiting with Create React App?

The CRA build\service-worker.js file now (v3 plus) includes code to handle skipWaiting:

self.addEventListener('message', (event) => {
  if (event.data && event.data.type === 'SKIP_WAITING') {
    self.skipWaiting();
  }
});

The register function serviceWorker.js file that is called in index.js now accepts a config parameter:

serviceWorker.register({
  onUpdate: registration => {
    const waitingServiceWorker = registration.waiting

    if (waitingServiceWorker) {
      waitingServiceWorker.addEventListener("statechange", event => {
        if (event.target.state === "activated") {
          window.location.reload()
        }
      });
      waitingServiceWorker.postMessage({ type: "SKIP_WAITING" });
    }
  }
});

This will skip waiting and then refresh the page once the update has been applied.


At serviceWorker.js file can find this code

if (config && config.onUpdate) {
    config.onUpdate(registration);
 }

So implement the config.onUpdate funtion

Create a file swConfig.js

export default {
 onUpdate: registration => {
   registration.unregister().then(() => {
   window.location.reload()
 })
},
onSuccess: registration => {
  console.info('service worker on success state')
  console.log(registration)
 },
}

At index.js send the implement function to serviceWorker

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import * as serviceWorker from './serviceWorker';
import swConfig from './swConfig'

ReactDOM.render(<App />, 
document.getElementById('root'));
serviceWorker.register(swConfig);

Check out this repo https://github.com/wgod58/create_react_app_pwaupdate