const useFetch = <T>(url: string): FetchResult<T> => {
const [data, setData] = useState<T | null>(null);
const [loading, setLoading] = useState<boolean>(true);
const [error, setError] = useState<Error | null>(null);
const fetchData = (): Promise<void> => {
setLoading(true);
return fetch(url)
.then((response) => {
if (!response.ok) {
throw new Error('HTTP error! Status: $ {response.status}');
}
return response.json() as Promise<T>;
})
.then((result) => {
setData(result);
setLoading(false);
})
.catch((error) => {
setError(error);
setLoading(false);
});
};
useEffect(() => {
fetchData();
}, [url]);
return { data, loading, error, fetchData };
};