useFetch.js

88 阅读1分钟
import { useState, useEffect } from "react";

const useFetch = (url) => {
  const [data, setData] = useState(null)
  const [isPending, setIsPending] = useState(true);
  const [error, setError] = useState(null);
  useEffect(() => {
    const abortController = new AbortController();

    setTimeout(() => {
      fetch(url, { signal: abortController.signal })
        .then(res => {
          console.log(res);
          if (!res.ok) {
            throw Error('Something went wrong!');
          }
          return res.json();
        })
        .then(data => {
          setData(data);
          setIsPending(false);
          setError(null);
        })
        .catch(err => {
          if (err.name === "AbortError") {
            console.log("Request aborted");
          } else {
            setIsPending(false);
            setError(err.message);
          }

        });
    }, 100);
    return () => abortController.abort();
  }, [])
  return { data, isPending, error };
}

export default useFetch;