使用axios自定义http钩子

时间:2020-07-27 15:27:49

标签: reactjs axios

我正在尝试创建我的第一个自定义钩子,但是不确定我是否在正确的轨道上。可能不是,这就是我要问的原因。首先,我不确定取消标记是否会像这样工作,或者在组件中实际使用此挂钩时是否需要使用它。

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

export default useApi = () => {
  const [data, setData] = useState([]);
  const [error, setError] = useState(false);
  const [loading, setLoading] = useState(false);

  const request = async () => {
    const ourRequest = Axios.CancelToken.source();
    setLoading(true);
    try {
      const response = await Axios(url, options);
      setData(response.data);
      setLoading(false);
    } catch (error) {
      setLoading(false);
      setError(error);
    }
    return () => {
      ourRequest.cancel();
    };
  };

  return { data, error, loading, request };
};

1 个答案:

答案 0 :(得分:1)

除了没有告诉axios关于cancelToken或适当处理取消错误外,这看起来还不错。 The Cancellation section of the documentation提供了有关此过程的一些详细信息,我已将其汇总到您的示例中:

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

export default useApi = () => {
  const [data, setData] = useState([]);
  const [error, setError] = useState(false);
  const [loading, setLoading] = useState(false);

  const request = async () => {
    const source = axios.CancelToken.source();
    setLoading(true);
    
    try {
      const response = await axios.get(url, { cancelToken: source.token });
      setData(response.data);
      setLoading(false);
    } catch (error) {
      if (axios.isCancel(error)) {
        // don't update state in case component is dismounting
      } else {
        setLoading(false);
        setError(error);
      }
    }

    return () => {
      source.cancel();
    };
  };

  return { data, error, loading, request };
};