Skip to content

Instantly share code, notes, and snippets.

@longsangstan
Last active May 22, 2020 00:38
Show Gist options
  • Save longsangstan/1fdbe963cacccddaea732052c5ca8ef6 to your computer and use it in GitHub Desktop.
Save longsangstan/1fdbe963cacccddaea732052c5ca8ef6 to your computer and use it in GitHub Desktop.
react hook for get
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