github.com/thanos-io/thanos@v0.32.5/pkg/ui/react-app/src/hooks/useFetch.ts (about) 1 import { useState, useEffect } from 'react'; 2 3 export type APIResponse<T> = { status: string; data: T }; 4 5 export interface FetchState<T> { 6 response: APIResponse<T>; 7 error?: Error; 8 isLoading: boolean; 9 } 10 11 export const useFetch = <T>(url: string, options?: RequestInit): FetchState<T> => { 12 const [response, setResponse] = useState<APIResponse<T>>({ status: 'start fetching' } as any); 13 const [error, setError] = useState<Error>(); 14 const [isLoading, setIsLoading] = useState<boolean>(true); 15 16 useEffect(() => { 17 const fetchData = async () => { 18 setIsLoading(true); 19 try { 20 const res = await fetch(url, { cache: 'no-store', credentials: 'same-origin', ...options }); 21 if (!res.ok) { 22 throw new Error(res.statusText); 23 } 24 const json = (await res.json()) as APIResponse<T>; 25 setResponse(json); 26 setIsLoading(false); 27 } catch (error) { 28 setError(error as Error); 29 setIsLoading(false); 30 } 31 }; 32 fetchData(); 33 }, [url, options]); 34 return { response, error, isLoading }; 35 };