Dinesh, how would this work with a functional component? I tried to translate it but it just keeps refreshing over and over. Here is my FC version, using Typescript
import { observer } from "mobx-react";
import React, { useEffect, useState } from "react";
import { useStores } from "../../contexts";
const semverGreaterThan = (versionA: string, versionB: string) => {
const versionsA = versionA.split(/\./g);
const versionsB = versionB.split(/\./g);
while (versionsA.length || versionsB.length) {
const a = Number(versionsA.shift());
const b = Number(versionsB.shift());
if (a === b) continue;
return a > b || isNaN(b);
}
return false;
}
const CacheBuster: React.FC<any> = ({ children }) => {
const store = useStores();
const [loading, setLoading] = useState(true);
const [isLatestVersion, setIsLatestVersion] = useState(false);
const refreshCacheAndReload = () => {
console.log('Clearing cache and hard reloading...')
if (caches) {
// Service worker cache should be cleared with caches.delete()
caches.keys().then(function(names) {
for (let name of names) caches.delete(name);
});
}
// delete browser cache and hard reload
window.location.reload();
};
useEffect(()=>{
fetch('/meta.json')
.then((response) => response.json())
.then((meta) => {
const latestVersion = meta.version;
const shouldForceRefresh = semverGreaterThan(latestVersion, store.appVersion);
if (shouldForceRefresh) {
console.log(`We have a new version - ${latestVersion}. Should force refresh`);
setLoading(false);
setIsLatestVersion(false);
}
else {
console.log(`You already have the latest version - ${latestVersion}. No cache refresh needed.`);
setLoading(false);
setIsLatestVersion(true);
}
})
.catch(err=>{
console.log('App could not be loaded. Check if meta.json file has been generated.');
});
//eslint-disable-next-line
}, []);
return children({ loading, isLatestVersion, refreshCacheAndReload });
}
export default observer(CacheBuster);
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
Dinesh, how would this work with a functional component? I tried to translate it but it just keeps refreshing over and over. Here is my FC version, using Typescript