Skip to content

Instantly share code, notes, and snippets.

@aneury1
Created March 2, 2023 16:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aneury1/885d3631c477392417248abbf7cc4461 to your computer and use it in GitHub Desktop.
Save aneury1/885d3631c477392417248abbf7cc4461 to your computer and use it in GitHub Desktop.
import { useState, useEffect, useCallback } from "react";
const useFetch = (url, options = {}, retries = 3) => {
const [data, setData] = useState(null);
const [loading, setLoading] = useState(false);
const [error, setError] = useState(null);
const [retryCount, setRetryCount] = useState(0);
const [isCancelled, setIsCancelled] = useState(false);
const fetchData = useCallback(async () => {
setLoading(true);
try {
const response = await fetch(url, options);
const data = await response.json();
if (!isCancelled) {
setData(data);
setLoading(false);
}
} catch (error) {
if (retryCount < retries && !isCancelled) {
setRetryCount(retryCount + 1);
} else {
setError(error);
setLoading(false);
}
}
}, [url, options, retryCount, retries, isCancelled]);
useEffect(() => {
fetchData();
return () => {
setIsCancelled(true);
};
}, [fetchData]);
const retry = useCallback(() => {
setRetryCount(0);
fetchData();
}, [fetchData]);
const cancel = useCallback(() => {
setIsCancelled(true);
setLoading(false);
}, []);
return { data, loading, error, retry, cancel };
};
export default useFetch;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment