import { useState, useEffect } from 'react'; export type APIResponse = { status: string; data?: T }; export interface FetchState { response: APIResponse; error?: Error; isLoading: boolean; } export const useFetch = (url: string, options?: RequestInit): FetchState => { const [response, setResponse] = useState>({ status: 'start fetching' }); const [error, setError] = useState(); const [isLoading, setIsLoading] = useState(false); useEffect(() => { const fetchData = async () => { setIsLoading(true); try { const res = await fetch(url, { cache: 'no-cache', credentials: 'same-origin', ...options }); if (!res.ok) { throw new Error(res.statusText); } const json = (await res.json()) as APIResponse; setResponse(json); setIsLoading(false); } catch (error) { setError(error); } }; fetchData(); }, [url, options]); return { response, error, isLoading }; };