Created
May 27, 2021 21:29
-
-
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
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 {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