Skip to Content

useFetch

A hook for making HTTP requests and managing the associated states. It provides loading, error, and success states along with the fetched data.

Parameters

  • url: string - The URL to fetch data from
  • reqOpt?: RequestInit - Optional request options (headers, method, etc.)

Returns

  • data: Data | undefined - The fetched data if successful
  • error: Error | undefined - Error information if the request failed
  • isLoading: boolean - Whether the request is in progress
  • isError: boolean - Whether the request resulted in an error
  • isSuccess: boolean - Whether the request was successful
  • refetch: () => void - Function to manually trigger a new fetch

Usage

import { useFetch } from '@rhinolabs/react-hooks'; function UserProfile() { const { data, error, isLoading, isError, isSuccess, refetch } = useFetch('https://api.example.com/user'); if (isLoading) { return <div>Loading...</div>; } if (isError) { return ( <div> Error: {error?.message} <button onClick={refetch}>Retry</button> </div> ); } return ( <div> {isSuccess && data && ( <> <h1>{data.name}</h1> <p>{data.email}</p> </> )} </div> ); }

Notes

  • Automatically fetches data on mount
  • Provides manual refetch capability
  • Handles JSON responses automatically
  • Manages all common request states
  • Supports custom request options
  • Returns undefined data on error
  • Success is based on HTTP 200 status
Last updated on