Skip to content

Instantly share code, notes, and snippets.

@coreyward
Forked from rexxars/bundleChecker.js
Created March 16, 2021 21:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save coreyward/2745c236fc4d9d6d6b40f786b87f08c1 to your computer and use it in GitHub Desktop.
Save coreyward/2745c236fc4d9d6d6b40f786b87f08c1 to your computer and use it in GitHub Desktop.
Sanity studio bundle update checker
import { useEffect } from "react"
import config from "config:sanity"
const BUNDLE_CHECK_INTERVAL = 60 * 1000
const CHANGES_AVAILABLE_MESSAGE =
"There are changes to the Studio. For the best results the page will be refreshed to update to the latest version of the Studio."
async function getCurrentHash() {
const basePath = (config.project && config.project.basePath) || "/"
const html = await window.fetch(basePath).then((res) => res.text())
const [, hash] = html.match(/app\.bundle\.js\?(\w+)/) || []
return hash
}
let hash = null
let interval = null
const BundleChecker = () => {
useEffect(() => {
getCurrentHash().then((newHash) => {
hash = newHash
})
interval = createInterval()
return () => clearInterval(interval)
}, [])
// We're a react component, in theory, so return null to not render anything
return null
}
export default BundleChecker
const createInterval = () =>
setInterval(async () => {
const newHash = await getCurrentHash()
if (hash && newHash !== hash) {
clearInterval(interval)
if (window.confirm(CHANGES_AVAILABLE_MESSAGE)) {
window.location.reload()
} else {
interval = createInterval()
}
}
}, BUNDLE_CHECK_INTERVAL)
{
"root": true,
"//": "...",
"parts": [
{
"implements": "part:@sanity/base/absolutes",
"path": "./bundleChecker.js"
}
]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment