Last active
July 31, 2019 18:23
-
-
Save FezVrasta/543f3fa5b365df64b2df5529b2b24921 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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