import { useEffect, useState } from 'react';
type State<T> =
| { status: 'loading' }
| { status: 'success'; data: T }
| { status: 'error'; error: Error };
export function useFetch<T>(url: string): State<T> {
const [state, setState] = useState<State<T>>({ status: 'loading' });
useEffect(() => {
const ctl = new AbortController();
setState({ status: 'loading' });
fetch(url, { signal: ctl.signal })
.then(async r => {
if (!r.ok) throw new Error(`HTTP ${r.status}`);
return r.json() as Promise<T>;
})
.then(data => setState({ status: 'success', data }))
.catch(error => { if (error.name !== 'AbortError') setState({ status: 'error', error }); });
return () => ctl.abort();
}, [url]);
return state;
}
Create a free account and build your private vault. Share publicly whenever you want.