How can you trigger a rerender of a React js component every minute?

Tyler Turden :

The Context:
A hook is defined and returns an object that contains the timestamp of the last time a file was modified.

I calculate the difference from the timestamp until now to show the user how long it was been since they have last saved.

const StageFooter = (props) => {
  const [, , meta] = useMetadata("Tenant Setup Data", "setupData")

  return (
    <StageControls>
      <div id="footer-start"></div>
      <SavingBlock key={meta?.modified}>
        {`Last saved ${
          meta.modified !== undefined ? formatDistanceToNow(meta.modified) : " "
        } ago`}
      </SavingBlock>
      <div id="footer-end"></div>
    </StageControls>
  )
}

export default StageFooter


The Problem:
The calculated difference from the timestamp until now does not update in real-time. For example, it would say "Last saved 10 minutes ago" but after a couple of minutes has passed the string still remains the same. It would only update if the user navigates away from the page then back or if the user refreshes the page.

With all this in mind, I'm basically looking to rerender the component every time a minute has passed so that the value is updated in real-time.

Thanks for your time!

Vencovsky :

You can create a effect that calls setTimeout every minute and when displaying the time, just subtract from the date.

You should also make a separete component for this, so if you use this inside a component, it won't rerender the hole component "every minute" and only rerender the text "x minutes since last change"

const [fakeCurrentDate, setFakeCurrentDate] = useState(new Date()) // default value can be anything you want

useEffect(() => {
    setTimeout(() => setFakeCurrentDate(new Date()), 60000)
}, [fakeCurrentDate])

...

{/* display time passed since*/}
<div>{fakeCurrentDate - modifiedDate}</div>

Working codesandbox (you will need to wait a minute to see changes)

But as Sterling Archer said in the comments, is this good? Well... who knows?


An advice

Another approach for this would be show a message Updated at XX:XX time instead of showing to the user how many minutes has passed. But this is much more about UX than the technology

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=19858&siteId=1