useFetch Hook

Data fetching hook with loading/error states

ReactAPIData Fetching

useFetch

Data fetching with loading and error states

Install Dependencies

1npm i axios

Copy source code and paste it in hooks/devsloka-hooks folder

hooks/devsloka-hooks/use-fetch.tsx

1"use client";
2import { useState, useEffect } from "react";
3
4export const useFetch = <T,>(url: string) => {
5 const [data, setData] = useState<T | null>(null);
6 const [loading, setLoading] = useState<boolean>(true);
7 const [error, setError] = useState<Error | null>(null);
8 const [refreshCount, setRefreshCount] = useState(0);
9
10 const refetch = () => {
11 setRefreshCount((prev) => prev + 1);
12 };
13
14 useEffect(() => {
15 const fetchData = async () => {
16 setLoading(true);
17 setError(null);
18
19 try {
20 const response = await fetch(url);
21 if (!response.ok) {
22 throw new Error(`HTTP error! status: ${response.status}`);
23 }
24 const result = (await response.json()) as T;
25 setData(result);
26 } catch (err) {
27 setError(err as Error);
28 } finally {
29 setLoading(false);
30 }
31 };
32
33 fetchData();
34 }, [url, refreshCount]);
35
36 return { data, loading, error, refetch };
37};