react-api-utils
Version:
A React utility library for making API calls using React Query and Axios, providing context-based configuration and custom hooks for seamless integration.
163 lines (155 loc) • 6.96 kB
TypeScript
import { AxiosRequestConfig } from 'axios';
import { default as default_2 } from 'react';
import { QueryClientConfig } from '@tanstack/react-query';
import { QueryKey } from '@tanstack/react-query';
import { UseMutationResult } from '@tanstack/react-query';
import { UseQueryOptions } from '@tanstack/react-query';
import { UseQueryResult } from '@tanstack/react-query';
/**
* Context provider for providing Axios instance and Query Client for API requests.
* This provider wraps your app to ensure that the API helper context is accessible and
* queries can be persisted using AsyncStorage.
*
*
* @example
* import {ApiHelperProvider} from 'react-api-utils';
*
* function App() {
* return (
* <ApiHelperProvider baseURL="https://api.example.com">
* <YourComponent />
* </ApiHelperProvider>
* );
* }
*
* @param {string} baseURL - The base URL for all API requests.
* @param {AxiosRequestConfig} [axiosConfig={}] - Optional configuration to extend or override the default Axios config.
* @param {QueryClientConfig} [queryClientConfig={}] - Optional configuration to extend or override the default React Query client config.
* @param {ReactNode} children - The children components that can access the API context.
*/
export declare const ApiHelperProvider: default_2.FC<ApiHelperProviderProps>;
/**
* @interface ApiHelperProviderProps
*
* Props for the `ApiHelperProvider` component which provides the necessary configurations
* for setting up API requests and managing query states using React Query.
*
* @property {string} baseURL - The base URL for the API requests. This is required to configure the Axios instance.
* @property {AxiosRequestConfig} [axiosConfig] - Optional custom Axios configuration. If not provided, the default configuration will be used.
* @property {QueryClientConfig} [queryClientConfig] - Optional configuration for React Query client. If not provided, default settings will be used.
* @property {React.ReactNode} children - The children components that will be wrapped by the `ApiHelperProvider`.
*
* @example
* // Example of using ApiHelperProvider with default configurations:
* <ApiHelperProvider baseURL="https://api.example.com">
* <YourComponent />
* </ApiHelperProvider>
*
* @example
* // Example with custom Axios and Query Client configurations:
* <ApiHelperProvider
* baseURL="https://api.example.com"
* axiosConfig={{ timeout: 5000 }}
* queryClientConfig={{ defaultOptions: { queries: { retry: 2 } } }}
* >
* <YourComponent />
* </ApiHelperProvider>
*
*
*/
export declare interface ApiHelperProviderProps {
baseURL: string;
axiosConfig?: AxiosRequestConfig;
queryClientConfig?: QueryClientConfig;
children: default_2.ReactNode;
}
/**
* @typedef HTTPMethod
*
* Represents the HTTP methods used for API requests.
* This type is used to specify the type of HTTP request in the API helper hook.
*
* @value {string} 'GET' - Fetches data from the server.
* @value {string} 'POST' - Sends data to the server to create a resource.
* @value {string} 'PUT' - Sends data to the server to update an existing resource.
* @value {string} 'PATCH' - Sends data to the server to partially update an existing resource.
* @value {string} 'DELETE' - Deletes a resource from the server.
*
* @example
* // Example of using the HTTPMethod type:
* const method: HTTPMethod = 'GET'; // GET request
* const postMethod: HTTPMethod = 'POST'; // POST request
*
* @see {@link https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods} for more information on HTTP methods.
*/
export declare type HTTPMethod = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';
export declare function useApiHelper<responseType, errorType>(options: {
method: 'GET';
url: string;
queryKey: QueryKey;
params?: Record<string, unknown>;
axiosOptions?: AxiosRequestConfig;
}): UseQueryResult<responseType, errorType>;
export declare function useApiHelper<responseType, errorType, payloadType>(options: {
method: 'POST' | 'PUT' | 'PATCH' | 'DELETE';
url: string;
params?: Record<string, unknown>;
axiosOptions?: AxiosRequestConfig;
onSuccess?: (data: responseType) => void;
onError?: (error: errorType) => void;
}): UseMutationResult<responseType, errorType, payloadType>;
/**
* @interface useApiHelperProps
*
* This interface defines the configuration options for the `useApiHelper` hook, which handles both
* API requests via React Query's `useQuery` and `useMutation`. It provides flexibility for making GET,
* POST, PUT, PATCH, and DELETE requests.
*
* @typeParam responseType - The expected data type returned by the API request (e.g., the shape of the response data).
* @typeParam errorType - The expected error type (e.g., error object or string).
* @typeParam payloadType - The type of the data to be sent with POST, PUT, PATCH, or DELETE requests.
*
* @property {string} url - The URL of the API endpoint.
* @property {Record<string, unknown>} [params] - Optional query parameters for GET requests.
* @property {payloadType} [data] - Optional data (payload) for POST, PUT, PATCH, or DELETE requests.
* @property {QueryKey} [queryKey] - Optional key used for caching and refetching data in `useQuery` (not needed for mutations).
* @property {AxiosRequestConfig} [axiosOptions] - Optional additional axios configuration such as headers.
* @property {HTTPMethod} method - The HTTP method (GET, POST, PUT, PATCH, DELETE).
* @property {(data: responseType) => void} [onSuccess] - Optional callback for successful API requests.
* @property {(error: errorType) => void} [onError] - Optional callback for failed API requests.
*
* @example
* // Example of GET request:
* const { data, error } = useApiHelper({
* method: 'GET',
* url: '/todos',
* queryKey: ['todos'],
* onSuccess: (data) => console.log(data),
* onError: (error) => console.error(error),
* });
*
* @example
* // Example of POST request:
* const { mutate, isPending, isError } = useApiHelper({
* method: 'POST',
* url: '/todos',
* data: { title: 'New Todo', completed: false },
* onSuccess: (data) => console.log('Data posted:', data),
* onError: (error) => console.error('Error posting data:', error),
* });
*
* const handlePost = (payload) => {
* mutate(payload);
* };
*/
export declare interface useApiHelperProps<responseType, errorType, payloadType = unknown> extends Omit<UseQueryOptions<responseType, errorType, responseType>, 'queryKey' | 'queryFn'> {
url: string;
params?: Record<string, unknown>;
data?: payloadType;
queryKey?: QueryKey;
axiosOptions?: AxiosRequestConfig;
method: HTTPMethod;
onSuccess?: (data: responseType) => void;
onError?: (error: errorType) => void;
}
export { }