iT邦幫忙

2023 iThome 鐵人賽

DAY 20
0
Modern Web

React進階班,用typescript與jest製作自己的custom hooks庫系列 第 20

[Day 20] useUploadProgress取得上傳進度條

  • 分享至 

  • xImage
  •  

我今天突然想要做一個上傳文件的進度條,我平常都用Axios來寫,所以這次就用axios來寫吧

他主要有兩個回傳值,一個是進度,一個是上傳函數,使用上傳函數上傳,我就能取得他的目前進度

import { useState } from "react";
import axios from "axios";

interface ProgressProps {
  progress: number;
  uploadFile: (file: File) => Promise<void>;
}

export const useUploadProgress = (): ProgressProps => {
  const [progress, setProgress] = useState<number>(0);

  const uploadFile = async (file: File): Promise<void> => {
    try {
      const formData = new FormData();
      formData.append("file", file);

      const config: any = {
        onUploadProgress: function (progressEvent: ProgressEvent) {
          const percentCompleted = Math.round(
            (progressEvent.loaded * 100) / progressEvent.total
          );
          setProgress(percentCompleted);
        },
      };

      await axios.post(
        "https://api.escuelajs.co/api/v1/files/upload",
        formData,
        config
      );
      setProgress(100); // If upload is successful, set progress to 100
    } catch (err: any) {
      console.error("Error uploading file:", err);
      setProgress(0); // Reset progress if there is an error
    }
  };

  return { progress, uploadFile };
};

完成~


上一篇
[Day 19] useThrottle 測試
下一篇
[Day 21] useUploadProgress測試
系列文
React進階班,用typescript與jest製作自己的custom hooks庫30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言