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!
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With