Skip to content

Instantly share code, notes, and snippets.

@KATT
Created December 15, 2022 15:58
Show Gist options
  • Star 23 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save KATT/62f0020f75183f8566452d105d0f0716 to your computer and use it in GitHub Desktop.
Save KATT/62f0020f75183f8566452d105d0f0716 to your computer and use it in GitHub Desktop.
import { Router } from 'next/router';
import { useEffect } from 'react';
import { publicConfig } from '~/shared/config';
import { trpc } from '~/utils/trpc';
let initVersion = publicConfig.GIT_COMMIT;
function useDetectVersionChange() {
const healthQuery = trpc.health.useQuery(undefined, {
refetchInterval: 10_000,
});
if (!initVersion && healthQuery.status === 'success') {
// This is only for development, in deployed environments the version is stable
initVersion = healthQuery.data.GIT_COMMIT;
}
const hasChanged =
healthQuery.status === 'success' &&
healthQuery.data.GIT_COMMIT !== initVersion;
return { hasChanged };
}
export function useHardNavigationOnVersionChange() {
const { hasChanged } = useDetectVersionChange();
useEffect(() => {
if (!hasChanged) {
return;
}
console.log(
'ℹ️ Detected version change, next navigation will reload the page',
);
const hardLinkOnNavigationChange = (target: string) => {
console.log('Doing hard navigation change due to version change');
window.location.href = target;
};
Router.events.on('routeChangeStart', hardLinkOnNavigationChange);
return () => {
Router.events.off('routeChangeStart', hardLinkOnNavigationChange);
};
}, [hasChanged]);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment