Skip to content

Instantly share code, notes, and snippets.

@cheskoxd
Created March 8, 2024 23:56
Show Gist options
  • Save cheskoxd/127c2d29754e457d68f3567afa8f301b to your computer and use it in GitHub Desktop.
Save cheskoxd/127c2d29754e457d68f3567afa8f301b to your computer and use it in GitHub Desktop.
import { useEffect, useState } from "react";
export const useFetch = <T>(url: string) => {
const [data, setData] = useState<T | any>();
const [loading, setLoading] = useState(true);
const [error, setError] = useState<Error | null>(null);
useEffect(() => {
const fetchData = async () => {
try {
const response = await fetch(url);
const jsonData = await response.json();
setData(jsonData);
} catch (err:any) {
setError(err);
} finally {
setLoading(false);
}
};
fetchData();
}, [url]);
return { data, loading, error };
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment