Created
October 11, 2019 09:55
-
-
Save freddi301/1b2356a9c3ee00ae4a2efe221fdf9abc to your computer and use it in GitHub Desktop.
useExpiration: returns true if given timestamp is in the future #react #hook
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { useState, useEffect } from "react"; | |
/** @description hook: returns true if given timestamp is in the future */ | |
export function useExpiration( | |
timestamp: number | null | undefined, | |
): boolean { | |
const visible = timestamp != null && Date.now() <= timestamp; | |
const [, forceRerender] = useState(0); | |
useEffect(() => { | |
if (visible && timestamp != null) { | |
const timeoutId = setTimeout( | |
forceRerender, | |
Math.max(0, timestamp - Date.now()), | |
increment, | |
); | |
return () => { | |
clearTimeout(timeoutId); | |
}; | |
} | |
return; | |
}, [visible, timestamp]); | |
return visible; | |
} | |
function increment(count: number): number { | |
return count + 1; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment