Function: useApi()
useApi<
T>(url,options?):UseApiReturn<T>
Defined in: use-api.ts:137
Custom React hook to perform API requests.
This hook simplifies the process of making HTTP requests from a React component, managing the loading state, data, and error handling for the request lifecycle.
On initialization, the hook triggers a fetch request to the specified URL
and tracks the loading status until the request is complete. It also provides
a refetch function to allow manual re-execution of the request, useful
in scenarios where data may need to be refreshed.
The hook can handle different HTTP methods and allows for custom headers and request bodies, making it flexible for various API interactions.
Only the latest request can update the state: when the inputs change, refetch
is called again, or the component unmounts, the request in flight is aborted
through an AbortSignal and its result is ignored. This prevents a slow,
outdated response from overwriting a newer one.
The response data is automatically parsed as JSON (204 and 205 responses
resolve to null), and any errors encountered
during the request process are caught and returned, allowing the consuming
component to handle them appropriately.
Type Parameters
T
T = unknown
The type of data expected in the response. This helps ensure type safety when consuming the data in a TypeScript environment.
Parameters
url
string
The endpoint from which to fetch data. This should be a fully qualified URL that the application can reach.
options?
Options for configuring the request, including HTTP method, headers, and body content.
Returns
UseApiReturn<T>
The result of the API request, including:
data: The fetched data, or null if there’s no data yet.loading: Indicates whether the request is currently being processed.error: TheErrorif the request failed (anApiErrorwithstatusandresponsefor non-2xx responses), or null if no error occurred.refetch: Function to manually refetch the data, useful for refreshing data in UI.
Example
const { data, loading, error, refetch } = useApi<MyDataType>('https://api.example.com/data');