Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save cicorias/d82925b1ed1aa4f1a3da2d0e059dd694 to your computer and use it in GitHub Desktop.
Save cicorias/d82925b1ed1aa4f1a3da2d0e059dd694 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