Skip to content

Instantly share code, notes, and snippets.

@mcanv
Created October 29, 2023 19:46
Show Gist options
  • Select an option

  • Save mcanv/9189757ec47b973b1b345f6ad131108e to your computer and use it in GitHub Desktop.

Select an option

Save mcanv/9189757ec47b973b1b345f6ad131108e to your computer and use it in GitHub Desktop.
Fetch Component
const { data, error, isLoading } = useFetch<FetchResult<object | any>>(
`https://jsonplaceholder.typicode.com/todos/1`
);
useEffect(() => {
console.log(data, error, isLoading);
}, [data, error, isLoading]);
import { useEffect, useState } from "react";
export interface FetchResult<T> {
data: T | null;
error: Error | null;
isLoading: boolean;
}
export function useFetch<T>(url: string): FetchResult<T> {
const [data, setData] = useState<T | null>(null);
const [error, setError] = useState<Error | null>(null);
const [isLoading, setLoading] = useState(true);
useEffect(() => {
async function fetchData() {
try {
const response = await fetch(url);
if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`);
}
const json: T = await response.json();
setData(json);
} catch (e: any) {
setError(e);
} finally {
setLoading(false);
}
}
fetchData();
}, [url]);
return { data, error, isLoading };
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment