Skip to content

Instantly share code, notes, and snippets.

@ryanflorence
Last active February 11, 2021 19:59
Show Gist options
  • Star 26 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save ryanflorence/2c50e77768e3f88b1c7251ef95ed01d3 to your computer and use it in GitHub Desktop.
Save ryanflorence/2c50e77768e3f88b1c7251ef95ed01d3 to your computer and use it in GitHub Desktop.
@franciscop
Copy link

franciscop commented Sep 21, 2020

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:

import React from 'react';
import { Link } from 'react-router-dom';

const init = new Date();
const timeout = 12 * 3600 * 1000;   // 12h

export default function StaleLink(props) {
  const isStale = new Date() - init > timeout;
  if (isStale) return <a href={props.to} {...props} />;
  return <Link {...props} />;
}

@Andarist
Copy link

@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.

@RodolfoSilva
Copy link

RodolfoSilva commented Sep 21, 2020

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} />
}

@franciscop
Copy link

@Andarist true, I was thinking of a previous discussion around <Link />, updated.

@nathanforce
Copy link

nathanforce commented Feb 11, 2021

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment