Skip to content

useFetch

Fetches a given URL synchronously. Returns the data, loading and error states.

Installation

npx rabbithook@latest add use-fetch

Usage

App.tsx
import useFetch from "@/hooks/use-fetch";
function Component() {
const { value, loading, error } = useFetch("https://jsonplaceholder.typicode.com/todos/1");
if (loading) {
return <p>Loading...</p>
}
if (error) {
return <p>Error: {error.message}</p>
}
return (
<p>{value.title}</p>
)
}

Code

use-fetch.ts
import useAsync from "../use-async";
const DEFAULT_OPTIONS = {
headers: { "Content-Type": "application/json" }
}
function useFetch<T>(url: string, options: RequestInit = {}, dependencies: unknown[] = []) {
return useAsync<T>(async () => {
return fetch(url, { ...DEFAULT_OPTIONS, ...options }).then(async res => {
if (res.ok) return res.json();
return res.json().then(json => Promise.reject(json));
})
}, dependencies)
}
export default useFetch;