axios-provider
v1.2.13
Published
## Overview
Readme
AxiosProvider Documentation
Overview
The AxiosProvider is a React component that provides a centralized way to manage multiple Axios instances in your application. It uses React Context to make HTTP methods and instances easily accessible throughout your application.
Installation
npm install axios-provider
# or
yarn add axios-providerBasic Usage
Setting Up the Provider
Wrap your application with the AxiosProvider and pass your API configurations as a prop.
import { AxiosProvider } from './path/to/AxiosProvider';
const configs = [
{
id: 'main-api',
baseURL: 'https://api.example.com'
},
{
id: 'secondary-api',
baseURL: 'https://secondary-api.example.com'
}
];
function App() {
return (
<AxiosProvider configs={configs}>
{/* Your application components */}
</AxiosProvider>
);
}Accessing Axios Instances
Use the useAxios hook to access HTTP methods or retrieve a specific Axios instance by ID.
import { useAxios } from './path/to/useAxios';
function MyComponent() {
const { get, post, getInstance } = useAxios();
const fetchData = async () => {
const response = await get('/users', 'main-api');
if (response.success) {
console.log('Data:', response.data);
} else {
console.error('Error:', response.error);
}
};
const postData = async () => {
const instance = getInstance('secondary-api');
if (instance) {
const response = await instance.post('/submit', { data: { foo: 'bar' } });
console.log('Response:', response.data);
}
};
return (
<div>
<button onClick={fetchData}>Fetch Data</button>
<button onClick={postData}>Post Data</button>
</div>
);
}Props
AxiosProvider
| Prop | Type | Required | Description |
| ------------ | -------------------- | -------- | ----------------------------------------------------------- |
| configs | InstanceConfig[] | Yes | Array of configurations for different API instances |
| children | ReactNode | Yes | Child components that will have access to the Axios context |
InstanceConfig Interface
interface InstanceConfig {
id: string; // Unique identifier for the instance
baseURL: string; // Base URL for the API
}Context Methods
The AxiosProvider exposes the following methods via the useAxios hook:
fetch
A generic method for making HTTP requests.
async function fetch(
path: string,
instanceId?: string,
options?: AxiosRequestConfig
): Promise<Response>;Convenience Methods
These methods simplify common HTTP requests:
get(path, instanceId?, options?)post(path, instanceId?, options?)put(path, instanceId?, options?)patch(path, instanceId?, options?)delete(path, instanceId?, options?)
Each method returns the same structure as fetch.
getInstance
Retrieves an Axios instance by its ID.
function getInstance(id: string): AxiosInstance | undefined;Response Structure
All HTTP methods return a response with the following structure:
interface Response {
data: any | undefined; // Response data if successful
status: number; // HTTP status code
success: boolean; // Whether the request was successful
headers: AxiosResponseHeaders | Partial<RawAxiosResponseHeaders> | undefined; // Response headers
error: string | undefined; // Error message if the request failed
}Advanced Usage
TypeScript Support
You can specify the response type for added type safety:
interface User {
id: number;
name: string;
}
function MyComponent() {
const { get } = useAxios();
const fetchUser = async () => {
const response = await get<User>('/users/1', 'main-api');
if (response.success) {
console.log('User name:', response.data?.name);
}
};
return <button onClick={fetchUser}>Fetch User</button>;
}Request Cancellation
Leverage AbortController to cancel ongoing requests:
import { useRef } from 'react';
import { useAxios } from './path/to/useAxios';
function MyComponent() {
const { fetch } = useAxios();
const controllerRef = useRef(new AbortController());
const fetchData = async () => {
const response = await fetch('/users', 'main-api', {
signal: controllerRef.current.signal
});
if (response.success) {
console.log('Data:', response.data);
} else {
console.error('Error:', response.error);
}
};
const cancelRequest = () => {
controllerRef.current.abort();
};
return (
<div>
<button onClick={fetchData}>Fetch Data</button>
<button onClick={cancelRequest}>Cancel Request</button>
</div>
);
}Features
- 🚀 Multiple API instance support
- 🔄 Automatic error handling
- 📡 Request cancellation with
AbortController - 🎯 Type-safe responses
- 🛠️ Convenient HTTP method helpers
- 🔍 Instance retrieval by ID
Best Practices
- Provide unique IDs for all API instance configurations.
- Use specific HTTP methods (
get,post, etc.) for better readability. - Handle success and error states explicitly in your components.
- Use TypeScript to enhance developer experience with type-safe requests and responses.
License
This project is licensed under the terms of the KSL License.
