Reputation: 1186
I have a PWA made by create-react-app. I have service worker enabled as by default.
import registerServiceWorker from './registerServiceWorker'
import App from './App'
ReactDOM.render(
<App />
, document.getElementById('root'))
registerServiceWorker()
On every publish I change package version, but my service-worker doesn't update.
I have tried with function
import { unregister } from './registerServiceWorker';
unregister()
as described here https://github.com/facebook/create-react-app
And this
navigator.serviceWorker.getRegistrations()
.then(registrationsArray => {
if (registrationsArray.length > 0) {
registrationsArray[0].update()
}
})
It doesn't work, what is my mistake? What is wrong? Thanks
Upvotes: 3
Views: 1667
Reputation: 832
Update to react-scripts
^3.2.0. Verify that you have the new version of serviceWorker.ts or .js. The old one was called registerServiceWorker.ts
and the register function did not accept a configuration object. Here is the new one: https://github.com/facebook/create-react-app/blob/3190e4f4a99b8c54acb0993d92fec8a859889a28/packages/cra-template/template/src/serviceWorker.js
Note that this solution only works well if you are Not lazy-loading.
then in index.tsx:
serviceWorker.register({
onUpdate: registration => {
alert('New version available! Ready to update?');
if (registration && registration.waiting) {
registration.waiting.postMessage({ type: 'SKIP_WAITING' });
}
window.location.reload();
}
});
The latest version of the ServiceWorker.ts register()
function accepts a config object with a callback function where we can handle upgrading. If we post a message SKIP_WAITING
this tells the service worker to stop waiting and to go ahead and load the new content after the next refresh. In this example I am using a javascript alert to inform the user. Please replace this with a custom toast.
The reason this postMessage
function works is because under the hood CRA is using workbox-webpack-plugin
which includes a SKIP_WAITING
listener.
More About Service Workers
good guide: https://redfin.engineering/how-to-fix-the-refresh-button-when-using-service-workers-a8e27af6df68
CRA issue discussing service worker cache: https://github.com/facebook/create-react-app/issues/5316
If you are not using CRA, you can use workbox directly: https://developers.google.com/web/tools/workbox
Upvotes: 2