npm create vite@latest --template react-ts
Included with Vite React-TS template
Create a reusable useFetch hook that encapsulates loading, error, and data state.
1 import { useState, useEffect } from 'react'; 2 3 type FetchState<T> = { 4 data: T | null; 5 loading: boolean; 6 error: Error | null; 7 }; 8 9 export function useFetch<T>(url: string): FetchState<T> { 10 const [state, setState] = useState<FetchState<T>>({ 11 data: null, loading: true, error: null, 12 }); 13 14 useEffect(() => { 15 const controller = new AbortController(); 16 setState(s => ({ ...s, loading: true, error: null })); 17 18 fetch(url, { signal: controller.signal }) 19 .then(r => { if (!r.ok) throw new Error(`HTTP ${r.status}`); return r.json(); }) 20 .then(data => setState({ data, loading: false, error: null })) 21 .catch(err => { 22 if (err.name !== 'AbortError') { 23 setState(s => ({ ...s, loading: false, error: err })); 24 } 25 }); 26 27 return () => controller.abort(); 28 }, [url]); 29 30 return state; 31 } 32 33 // Usage: 34 // const { data: posts, loading, error } = useFetch<Post[]>('/api/posts');
useFetch<Post[]>("/api/posts") returns typed data with loading statesSign in to share your feedback and join the discussion.