npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2025 – Pkg Stats / Ryan Hefner

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-provider

Basic 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

  1. Provide unique IDs for all API instance configurations.
  2. Use specific HTTP methods (get, post, etc.) for better readability.
  3. Handle success and error states explicitly in your components.
  4. Use TypeScript to enhance developer experience with type-safe requests and responses.

License

This project is licensed under the terms of the KSL License.