Skip to content

Instantly share code, notes, and snippets.

@jonocairns
Created May 27, 2021 21:29
Show Gist options
  • Save jonocairns/c3c21a1dee5d356bf9a9a0cabf6f8c2c to your computer and use it in GitHub Desktop.
Save jonocairns/c3c21a1dee5d356bf9a9a0cabf6f8c2c to your computer and use it in GitHub Desktop.
CRA version checker - uses material-ui and snackbar libraries which can be easily replaced with other frameworks
import {Button} from '@material-ui/core';
import {CloseOutlined} from '@material-ui/icons';
import {addBreadcrumb, BreadcrumbCategory} from 'addBreadcrumb';
import {useSnackbar} from 'notistack';
import React, {useState} from 'react';
const MANIFEST = '/asset-manifest.json';
const POLL_INTERVAL = 60000;
export const VersionCheck: React.FC = ({children}) => {
const {enqueueSnackbar, closeSnackbar} = useSnackbar();
const [dismissedVersion, setDismissedVersion] = useState('');
React.useEffect(() => {
const getLatestVersion = async () => {
const response = await fetch(MANIFEST);
return await response.text();
};
const attachExceptionBreadcrumb = (exception: Error) => {
addBreadcrumb(BreadcrumbCategory.Version, 'Issue attempting to fetch manifest file for version check', {
exception,
});
};
const init = async () => {
try {
const latestVersion = await getLatestVersion();
localStorage.setItem('tend-version', latestVersion);
} catch (ex) {
attachExceptionBreadcrumb(ex);
} finally {
setTimeout(poll, POLL_INTERVAL);
}
};
const poll = async () => {
try {
const currentVersion = localStorage.getItem('tend-version');
const latestVersion = await getLatestVersion();
if (currentVersion && currentVersion !== latestVersion && latestVersion !== dismissedVersion) {
enqueueSnackbar('A new version is available', {
variant: 'info',
persist: true,
preventDuplicate: true,
action: (key) => (
<>
<Button color="inherit" onClick={() => window.location.reload()}>
Refresh
</Button>
<Button
color="inherit"
variant="text"
onClick={() => {
setDismissedVersion(latestVersion);
closeSnackbar(key);
}}>
<CloseOutlined />
</Button>
</>
),
});
}
} catch (ex) {
attachExceptionBreadcrumb(ex);
} finally {
setTimeout(poll, POLL_INTERVAL);
}
};
if (process.env.NODE_ENV === 'production') {
init();
}
}, [closeSnackbar, dismissedVersion, enqueueSnackbar]);
return <>{children}</>;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment