Skip to content

Commit

Permalink
🐛 fix fetch hook bug
Browse files Browse the repository at this point in the history
  • Loading branch information
JohnsonMao committed Jan 28, 2024
1 parent ed27828 commit bcdbb96
Showing 1 changed file with 8 additions and 5 deletions.
13 changes: 8 additions & 5 deletions hooks/useFetch.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,21 +3,24 @@ import { useEffect, useState } from 'react';
const useFetch = (url, { initialValue } = {}) => {
const [data, setData] = useState(initialValue);
const [isFetching, setIsFetching] = useState(true);
const [isError, setIsError] = useState(false);

useEffect(() => {
const abortController = new AbortController();
let pass = true;

setIsFetching(true);
setIsError(false);

fetch(url, { signal: abortController.signal })
fetch(url)
.then((res) => res.json())
.then((json) => setData(json))
.then((json) => pass && setData(json))
.catch(() => setIsError(true))
.finally(() => setIsFetching(false));

return () => abortController.abort();
return () => pass = false;
}, [url]);

return { data, isFetching };
return { data, isFetching, isError };
};

export default useFetch;

0 comments on commit bcdbb96

Please sign in to comment.