Created
November 5, 2019 10:50
-
-
Save danielrbradley/51288dd8554ad678efddf0094687ca92 to your computer and use it in GitHub Desktop.
Integrating service worker auto-refresh with reach router
This file contains hidden or 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
import React, { useEffect, useRef } from 'react'; | |
import { Location } from '@reach/router'; | |
import { register } from '../serviceWorker'; | |
/** | |
* Include this component around your router to register a service worker to cache the application | |
* so it works offline. Then, when the application has automatically updated itself, intercept the | |
* Reach router location change and do a hard browser navigation to enble the application updates | |
* to be applied. | |
* @example | |
* <OfflineApp> | |
* <Router> | |
* <HomeRoute path="/" /> | |
* </Router> | |
* </OfflineApp> | |
*/ | |
export const OfflineApp: React.FC = props => { | |
const updateReadyRef = useRef(false); | |
useEffect(() => { | |
register({ | |
onSuccess: () => console.log('Ready to work offline'), | |
onUpdate: () => { | |
updateReadyRef.current = true; | |
}, | |
}); | |
}, []); | |
return ( | |
<Location> | |
{({ location }) => { | |
if (updateReadyRef.current) { | |
window.location.href = location.href; | |
} | |
return props.children; | |
}} | |
</Location> | |
); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Turns out just doing a hard refresh isn't enough to pick up the update on a mobile device because the old instance is still loaded until the refresh finishes. Should look at how to work around this otherwise it seems the refresh will only happen when the device is restarted.