Created
February 10, 2024 23:07
-
-
Save sturmenta/4b30a8f62aad3f77776973d7f9f4aad2 to your computer and use it in GitHub Desktop.
show remaining time in react (59:59 - 00:00) with dayjs
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
// initialize this config when the app start as importing the file (import "@/config/dayjs-config") | |
import dayjs from "dayjs" | |
import duration from "dayjs/plugin/duration" | |
import utc from "dayjs/plugin/utc" | |
dayjs.extend(duration) | |
dayjs.extend(utc) |
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 dayjs from "dayjs" | |
import { useEffect, useState } from "react" | |
import { Text } from "react-native" | |
// NOTE: | |
// show max 59:59 time remaining | |
// show 00:00 when time is expired | |
export const RemainingTime = ({ expired_time }: { expired_time: string }) => { | |
const [time, setTime] = useState("00:00") | |
const _setTime = () => { | |
const diff = dayjs(expired_time).diff(dayjs()) | |
if (diff < 0) return setTime("00:00") | |
const dur = dayjs.duration(diff) | |
const remaining = dayjs.utc(dur.asMilliseconds()).format("mm:ss") | |
setTime(remaining) | |
} | |
useEffect(() => { | |
_setTime() // don't wait 1 second to show the time | |
const setTimeInterval = setInterval(_setTime, 1000) | |
return () => { | |
clearInterval(setTimeInterval) | |
} | |
}, []) | |
return <Text>{time}</Text> | |
} | |
// why use utc? -> https://github.com/iamkun/dayjs/issues/641#issuecomment-643924034 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment