Last active
May 22, 2020 00:38
-
-
Save longsangstan/1fdbe963cacccddaea732052c5ca8ef6 to your computer and use it in GitHub Desktop.
react hook for get
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 { useCallback, useEffect, useState } from "react"; | |
const useGet = <T>(endpoint: string) => { | |
const [data, setData] = useState<T | null>(null); | |
const [isLoading, setIsLoading] = useState(false); | |
const [error, setError] = useState(""); | |
const fetchData = useCallback(async () => { | |
setError(""); | |
setIsLoading(true); | |
try { | |
const response = await fetch(endpoint); | |
if (!response.ok) { | |
throw new Error(`API request failed - ${response.status}`); | |
} | |
setData(await response.json()); | |
} catch (e) { | |
setError((e as Error).message); | |
} | |
setIsLoading(false); | |
}, [endpoint]); | |
useEffect(() => { | |
fetchData(); | |
}, [fetchData]); | |
return { data, isLoading, error, fetchData }; | |
}; | |
export default useGet; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment