Created
March 2, 2023 16:36
-
-
Save aneury1/885d3631c477392417248abbf7cc4461 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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