-
-
Save ryanflorence/2c50e77768e3f88b1c7251ef95ed01d3 to your computer and use it in GitHub Desktop.
| // If the user has been on the page for over 12 hours, the next link | |
| // click will do a full page transition to get new code | |
| import React from "react"; | |
| import { BrowserRouter, useLocation } from "react-router-dom"; | |
| let hour = 3600000; | |
| export default function StaleAppRouter(props) { | |
| let [isStale, setIsStale] = useState(false); | |
| useEffect(() => { | |
| let id = setTimeout(() => { | |
| setIsStale(true) | |
| }, hour * 12) | |
| return () => clearTimeout(id) | |
| }, []); | |
| return <BrowserRouter forceRefresh={isStale} /> | |
| } | |
| // now replace your <BrowserRouter /> with a <StaleAppRouter /> |
@franciscop the StaleAppRouter would have to be rerendered in your case to make this work and most likely it wouldn't be rendered in your app so this wouldn't work.
Thanks @ryanflorence
I've made some changes and added typescript.
import React from "react";
import { BrowserRouter, BrowserRouterProps } from "react-router-dom";
interface StaleAppRouterProps extends BrowserRouterProps {
forceRefreshAfterDelay?: number;
}
export default function StaleAppRouter(props: StaleAppRouterProps) {
const {
forceRefreshAfterDelay = 12 * 60 * 60 * 1000,
...rest
} = props;
const [isStale, setIsStale] = useState(false);
useEffect(() => {
const id = setTimeout(() => {
setIsStale(true)
}, forceRefreshAfterDelay)
return () => clearTimeout(id)
}, [forceRefreshAfterDelay]);
return <BrowserRouter forceRefresh={isStale} {...rest} />
}@Andarist true, I was thinking of a previous discussion around <Link />, updated.
It seems that modifying forceRefresh after initialization is unsupported. Has anyone had success with the examples here?
Comment from Michael on the prop:
remix-run/history#477 (comment)
BrowserRouter source (history is never reinitialized):
https://github.com/ReactTraining/react-router/blob/346153e38365e6a88657ce2e4e5acada290fc430/packages/react-router-dom/modules/BrowserRouter.js#L10-L16
The suggested solution looks to be using key, but that would result in a full remount of the app tree below Router, which is (probably) undesirable.
I would prefer this, since you probably want a full refresh if the whole site has been opened more than 12h, not only if a single given component has been opened 12h. Also removes potential issues with the timeout: