useFetch()
useFetch<
T
>(url
):object
Defined in: src/hooks/async/useFetch.ts:35
A custom React hook to fetch data from an API and manage its state. Automatically handles loading, error, and result states. Supports cancellation of the fetch operation on component unmount.
Type Parameters
• T
The type of the data to fetch.
Parameters
url
string
The API endpoint to fetch data from.
Returns
object
An object containing:
data
: The fetched data or null if not available.error
: An error object if the fetch operation fails.loading
: A boolean indicating whether the fetch operation is in progress.
data
data:
null
|T
error
error:
null
|Error
loading
loading:
boolean
Example
tsx
import { useFetch } from '@zl-asica/react';
const MyComponent = () => {
const { data, error, loading } = useFetch<{ message: string }>(
'https://api.example.com/endpoint'
);
if (loading) return <p>Loading...</p>;
if (error) return <p>Error: {error.message}</p>;
return <p>Data: {data?.message}</p>;
};