Search code examples
javascriptreactjsprogressive-web-appsnetlify

React PWA - enforce update on click


community,

I am doing "programmatic presentations" using React (CLI) and PWA (register()). Everything works just fine, but anytime some changes are made, the URL of the final app needs to be changed so all changes are loaded.

The whole mechanism works like this:

  1. The final app is sent to Github,
  2. this private repo is connected to Netlify,
  3. Netlify generates a unique URL,
  4. users visit this Netlify URL and hit "add to home screen" on iPad,
  5. the whole app runs under the Safari engine.
  6. If any change in the code is made, I have to change the link in Netlify and send this new link to a people.

The process mentioned above works just fine, but honestly, it would be nice to have some kind of functionality that allows request latest update on demand - let's say - on click of a button.

Is something like that possible?

Thank you for comments!

Kind Regards Linc


Solution

  • 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()
      })
     },
    }
    

    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