-1

Countdown với Reactjs Typescript sử dụng momentjs

  1. Định nghĩa:
type $Parse = {
    months?: string;
    days?: string;
    hours?: string;
    minutes?: string;
    seconds?: string;
};

type $Time = {
    timeString: string;
    diffTimes: number;
    stop: boolean;
    parse: $Parse;
    initTime?: $Parse;
};

type $Props = {
    timeThen: Moment;
    initTime?: $Parse;
};
  1. Tạo hook xử lý logic:
'use client';
import moment, { Moment } from 'moment';
import { useState } from 'react';

export function useCountDown({ timeThen, initTime }: $Props) {
    const [time, setTime] = useState({} as $Time);

    const padTime = (val: any) => {
        return val.toString().padStart(2, '0') as string;
    };

    const onConstrueTime = (timeThen: any) => {
        const now = moment();
        const then = moment(timeThen);

        const diffTimes = then.diff(now);

        const remaining = moment.duration(diffTimes);

        const months = padTime(remaining.months());
        const days = padTime(remaining.days());
        const hours = padTime(remaining.hours());
        const minutes = padTime(remaining.minutes());
        const seconds = padTime(remaining.seconds());

        return {
            timeString:
                `ngày: ${days} - giờ: ${hours} - phút :${minutes} - giây: ${seconds}`.toString(),
            diffTimes,
            stop: diffTimes < 1,
            parse: { months, days, hours, minutes, seconds },
        } as const;
    };

    const onCountdown = () => {
        const interval = setInterval(() => {
            const result = onConstrueTime(timeThen);

            if (result?.stop) {
                setTime({ ...result, initTime });
                clearInterval(interval);
            } else {
                setTime({ ...result });
            }
        }, 1000);
    };
    return { onCountdown, onConstrueTime, time };
}
  1. Cách dùng: Tại component gọi trong lifecycirle : ví dụ time then là 30 giây nữa
   const { time, onCountdown } = useCountDown({
        timeThen: moment().add(30, 'seconds'),
    });

    useEffect(() => {
        onCountdown();
    }, []);

    type KeyParse = keyof typeof time.parse;

    console.log('time :>> ', time);

output time:

{
    "timeString": "ngày: 00 - giờ: 00 - phút :00 - giây: 05",
    "diffTimes": 5485,
    "stop": false,
    "parse": {
        "months": "00",
        "days": "00",
        "hours": "00",
        "minutes": "00",
        "seconds": "05"
    }
}

Thích thì mình chỉnh lại xí là được, thấy clean & clear code rồi đúng hông

Phần tiếp theo: Edit JSON


All rights reserved

Viblo
Hãy đăng ký một tài khoản Viblo để nhận được nhiều bài viết thú vị hơn.
Đăng kí