Skip to main content

Function: useApi()

useApi<T>(url, options?): UseApiReturn<T>

Defined in: use-api.ts:65

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.

The response data is automatically parsed as JSON, 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?​

UseApiOptions

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: Contains any error message if the request fails, 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');