API Client Documentation for React + React Query Application
This document explains the structure and usage of the queryAsync
function, your custom API client in the React + React Query application.
Purpose:
- Provide a centralized and consistent way to make API requests from your React components.
- Simplify API interactions by handling URL construction, headers, and error responses.
Key Features:
- Type-safe: Enforces specific types for request and response data using interfaces.
- Token handling: Optionally includes an access token in the Authorization header for authenticated requests.
- Query parameter serialization: Automatically constructs the API URL with any provided query parameters.
- Error handling: Returns a normalized error object in case of API failures.
- Flexibility: Supports various HTTP methods (
type
), request data (data
), and timeout configuration.
Function Breakdown:
queryAsync
:- Accepts an
ApiClientRequestType
object containing details about the API request. - Uses
axios
library to make the actual HTTP request. - Serializes the API URL with base URL and query parameters using
serialize
function. - Includes access token in Authorization header if provided.
- Parses the API response and resolves with data on success or rejects with a normalized error object on failure.
- Accepts an
Request Types:
path
: Endpoint URL relative to the base URL.type
: HTTP method (e.g.,GET
,POST
,PUT
, etc.).data
: Optional data to be sent in the request body.queryParams
: Optional object containing query parameters.token
: Optional access token for authenticated requests.additionalHeaders
: Optional object for additional headers.mockType
: Optional type for using local or swagger mocks (for development, not used in production).timeout
: Optional timeout value for the request in milliseconds.
Response:
- On success, resolves with the parsed data object from the API response.
- On failure, rejects with an error object containing
errorCode
anderrorMessage
.
Usage Example:
javascript
export const useBlogs = (page: number, limit: number = 10, search?: string) => {
return useAuthenticatedQuery(['blogs', `${page}`], (token) => {
return queryAsync<BlogListType>({
path: `/blogs`,
type: 'GET',
queryParams: {
page: page + 1,
limit,
...(search && {
search,
}),
},
token,
});
});
};
Benefits:
- Improved code organization and reusability for API interactions.
- Centralized error handling for consistent user experience.
- Enhanced type safety and maintainability.
Additional Notes:
- Refer to the
api
constant file for base URL and other API-related configurations. - Consider using
useQuery
oruseMutation
from React Query with this client for efficient data fetching and caching. - The
mockType
feature is specifically for development purposes and not used in production environments.