markvanwijnen/ServiceWorkerUpdateListener

Usage in React Component?

Closed this issue · 1 comments

Great library! I am trying to make it work in React, inside my top-level 'app.js' component. I've tried doing thus in the function component:

const listener = new ServiceWorkerUpdateListener(); listener.onupdateinstalling = (installingevent) => { console.log("SW installed"); }; listener.onupdatewaiting = (waitingevent) => { console.log("new update waiting"); };

And I'm not seeing anything in the console. The next step is to try useState() and after that I can try some other things. I'm sure if I were better at JS and React it would trivial to figure this out. I'm not sure how much effort I should put toward making your library work in React because it's not all that hard to achieve my purposes otherwise thanks to some blogs out there. If I can make this work perhaps I'd fork your code and make a React library, though if I'm just going to take your work maybe you don't want to answer my problem for me.

Anyway, great job on this. There's a surprising dearth of tools and support for doing anything but the most superficial PWA tasks. I think a great addition to your project here would be to handle reloading more comprehensively, as is discussed in the post where I originally found your thing here:

https://redfin.engineering/how-to-fix-the-refresh-button-when-using-service-workers-a8e27af6df68

I just realized I haven't added the service worker's registration to the listener. I'll leave this up and update my progress in case anyone else wants to use this in React.

edit

aaaaand it works! Just had to add the registration to the listener. Here's the complete code, running my App() function componenet:

`
const listener = new ServiceWorkerUpdateListener();
listener.onupdateinstalling = (installingevent) => {
console.log("SW installed");
};
listener.onupdatewaiting = (waitingevent) => {
console.log("new update waiting");
};

navigator.serviceWorker
.getRegistration()
.then((reg) => listener.addRegistration(reg));
`

From here it will be trivial to use these events however I need anywhere in the app. The only remaining challenge is to reload multiple clients. Of course the above code should be inside appropriate React life cycle method.

I'll mark the issue closed. I hope this may be helpful for anyone. I also hope this repo gets more attention because it's really useful.