wuxianqiang / blog

博客系列
17 stars 4 forks source link

写一个Hook发送请求 #261

Open wuxianqiang opened 4 years ago

wuxianqiang commented 4 years ago
import React, { useState } from 'react';

function useFetchData(url, timeout) {
  const [data, setData] = useState([]);
  const [loading, setLoading] = useState(false)
  const [error, setError] = useState(false)
  function init() {
    setData([])
    setLoading(true)
    setError(false)
  }
  async function load() {
    init()
    setLoading(true);
    try {
      const instance = axios.create();
      const result = await instance.get(url, { timeout });
      setData(result)
    } catch (error) {
      setError(true)
    }
    setLoading(false)
  }
  return [data, loading, error, load]
}