Skip to content

Commit

Permalink
docs: Add more detailed docs for useApi hook
Browse files Browse the repository at this point in the history
sleepinzombie committed Nov 3, 2024
1 parent 6bd0756 commit ecf24c8
Showing 1 changed file with 27 additions and 5 deletions.
32 changes: 27 additions & 5 deletions src/hooks/use-api.ts
Original file line number Diff line number Diff line change
@@ -9,7 +9,7 @@ interface UseApiOptions {
method?: "GET" | "POST" | "PUT" | "DELETE";
/** Headers to include in the request. */
headers?: HeadersInit;
/** The body of the request for methods that require it (e.g., POST, PUT). */
/** The body of the request for methods that require it (e.g., `POST`, `PUT`). */
body?: BodyInit;
}

@@ -32,10 +32,32 @@ interface UseApiReturn<T> {
/**
* Custom React hook to perform API requests.
*
* @template T
* @param {string} url - The endpoint from which to fetch data.
* @param {UseApiOptions} [options] - Options for configuring the request.
* @returns {UseApiReturn<T>} The result of the API request.
* 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.
*
* @template T The type of data expected in the response. This helps ensure type safety
* when consuming the data in a TypeScript environment.
* @param {string} url - The endpoint from which to fetch data. This should be a fully
* qualified URL that the application can reach.
* @param {UseApiOptions} [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`: 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');

0 comments on commit ecf24c8

Please sign in to comment.