Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement skipWaiting with Create React App?

I would like users to be able to update on the spot when a new service worker is available and waiting? I'm already able to show a pop up when new update is available but I would like to add a button to force update on the spot. I understand this can be achieved with calling skipWaiting but not sure how to implement it with a Create React App. Have anyone able to achieve this? Would appreciate the help. Thank you!

like image 416
unspeakable29 Avatar asked Oct 20 '18 09:10

unspeakable29


2 Answers

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.

like image 130
user1843640 Avatar answered Sep 28 '22 09:09

user1843640


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

like image 28
ZedPai Avatar answered Sep 28 '22 08:09

ZedPai