Skip to content

Instantly share code, notes, and snippets.

@FezVrasta
Last active July 31, 2019 18:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save FezVrasta/543f3fa5b365df64b2df5529b2b24921 to your computer and use it in GitHub Desktop.
Save FezVrasta/543f3fa5b365df64b2df5529b2b24921 to your computer and use it in GitHub Desktop.
const ServiceWorkerContext = React.createContext();
export const ServiceWorkerProvider = ({ children }) => {
const [waitingServiceWorker, setWaitingServiceWorker] = useState(null);
const [isUpdateAvailable, setUpdateAvailable] = useState(false);
React.useEffect(() => {
serviceWorker.register({
onUpdate: registration => {
setWaitingServiceWorker(registration.waiting);
setUpdateAvailable(true);
}
});
}, []);
React.useEffect(() => {
// We setup an event listener to automatically reload the page
// after the Service Worker has been updated, this will trigger
// on all the open tabs of our application, so that we don't leave
// any tab in an incosistent state
waitingServiceWorker.addEventListener('statechange', event => {
if (event.target.state === 'activated') {
window.location.reload();
}
});
}, [waitingServiceWorker]);
const value = React.useMemo(() => ({
isUpdateAvailable,
updateAssets: () => {
if (waitingServiceWorker) {
// We send the SKIP_WAITING message to tell the Service Worker
// to update its cache and flush the old one
waitingServiceWorker.postMessage({ type: 'SKIP_WAITING' });
}
}
}), [isUpdateAvailable, waitingServiceWorker]);
return (
<ServiceWorkerContext.Provider value={value}>
{children}
</ServiceWorkerContext.Provider>
);
}
// With this React Hook we'll be able to access `isUpdateAvailable` and `updateAssets`
export const useServiceWorker = () => {
return React.useContext(ServiceWorkerContext);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment