Skip to content

Instantly share code, notes, and snippets.

@danielrbradley
Created November 5, 2019 10:50
Show Gist options
  • Save danielrbradley/51288dd8554ad678efddf0094687ca92 to your computer and use it in GitHub Desktop.
Save danielrbradley/51288dd8554ad678efddf0094687ca92 to your computer and use it in GitHub Desktop.
Integrating service worker auto-refresh with reach router
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>
);
};
@danielrbradley
Copy link
Author

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment