Created
October 3, 2024 07:54
-
-
Save freddi301/0f3c47aab40a3d5d8927ac7b61db7a35 to your computer and use it in GitHub Desktop.
React hook use adjusted refreshing value
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
// adjust refreshing value in time for more pleasant loading indicator animation | |
// it is true if it was awlays true in the last 0.3 seconds | |
// it stays true for at least 1.0 second | |
function useAdjustedRefreshingValue(isRefreshing: boolean): boolean { | |
const DO_NOT_SHOW_BEFORE_MILLIS = 300; | |
const SHOW_FOR_AT_LEAST_MILLIS = 1000; | |
const [adjustedIsRefreshing, setAdjustedIsRefreshing] = | |
React.useState(isRefreshing); | |
const [isRefrescingSince, setIsRefreshingSince] = React.useState(0); | |
React.useEffect(() => { | |
if (isRefreshing) { | |
setIsRefreshingSince(Date.now()); | |
const timeout = setTimeout(() => { | |
setAdjustedIsRefreshing(true); | |
}, DO_NOT_SHOW_BEFORE_MILLIS); | |
return () => clearTimeout(timeout); | |
} | |
return () => undefined; | |
}, [isRefreshing]); | |
React.useEffect(() => { | |
if (!isRefreshing) { | |
const timeout = setTimeout( | |
() => setAdjustedIsRefreshing(false), | |
Math.max( | |
0, | |
DO_NOT_SHOW_BEFORE_MILLIS + | |
SHOW_FOR_AT_LEAST_MILLIS - | |
(Date.now() - isRefrescingSince) | |
) | |
); | |
return () => clearTimeout(timeout); | |
} | |
return () => undefined; | |
}, [isRefrescingSince, isRefreshing]); | |
return adjustedIsRefreshing; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment