0
0
Lập trình
Harry Tran
Harry Tran106580903228332612117

Hướng Dẫn Tạo Bộ Đếm Ngược Với ReactJS và TypeScript Sử Dụng Moment.js

Đăng vào 3 tuần trước

• 3 phút đọc

Hướng Dẫn Tạo Bộ Đếm Ngược Với ReactJS và TypeScript Sử Dụng Moment.js

1. Định Nghĩa Kiểu Dữ Liệu

Để khởi đầu, chúng ta định nghĩa một số kiểu dữ liệu cần thiết cho bộ đếm ngược:

typescript Copy
// Kiểu dữ liệu để phân tích thời gian
type $Parse = {
    months?: string;
    days?: string;
    hours?: string;
    minutes?: string;
    seconds?: string;
};

// Kiểu dữ liệu thời gian
type $Time = {
    timeString: string;
    diffTimes: number;
    stop: boolean;
    parse: $Parse;
    initTime?: $Parse;
};

// Định nghĩa các thuộc tính cho hook
type $Props = {
    timeThen: Moment;
    initTime?: $Parse;
};

2. Tạo Hook Xử Lý Logic Bộ Đếm Ngược

Tiếp theo, chúng ta sẽ tạo một hook để xử lý các logic liên quan đến đếm ngược:

typescript Copy
'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 };
}

3. Cách Sử Dụng Hook Trong Component

Để sử dụng hook mà chúng ta đã tạo, ta có thể thực hiện như sau:

typescript Copy
const { time, onCountdown } = useCountDown({
    timeThen: moment().add(30, 'seconds'),
});

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

type KeyParse = keyof typeof time.parse;

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

Kết Quả Đầu Ra

Khi gọi hook, ta sẽ nhận được một đối tượng chứa thông tin của bộ đếm ngược, ví dụ như sau:

json Copy
{
    "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"
    }
}

Bạn có thể tùy chỉnh thêm cho phù hợp với nhu cầu của mình. Mã nguồn đã được tối ưu và rõ ràng, dễ hiểu cho người dùng.

Phần Tiếp Theo: Chỉnh Sửa Dữ Liệu JSON

source: viblo

Gợi ý câu hỏi phỏng vấn
Không có dữ liệu

Không có dữ liệu

Bài viết được đề xuất
Bài viết cùng tác giả

Bình luận

Chưa có bình luận nào

Chưa có bình luận nào