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 fromreqOpt?:RequestInit- Optional request options (headers, method, etc.)
Returns
data:Data | undefined- The fetched data if successfulerror:Error | undefined- Error information if the request failedisLoading:boolean- Whether the request is in progressisError:boolean- Whether the request resulted in an errorisSuccess:boolean- Whether the request was successfulrefetch:() => 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