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 🙏

© 2024 – Pkg Stats / Ryan Hefner

multi-api-fetcher

v1.0.1

Published

An npm package for fetching data from multiple APIs using TanStack Query

Downloads

135

Readme

Documentation for multi-api-fetcher Package

multi-api-fetcher

multi-api-fetcher is a simple and powerful React hook for fetching data from multiple APIs using TanStack Query (formerly React Query) and axios. It allows you to make multiple API requests, manage their loading states, and handle errors with ease.

Features

  • Fetch data from multiple APIs in one hook.
  • Efficiently handles multiple loading and error states.
  • Uses TanStack Query’s caching and background fetching capabilities.
  • Simplifies API fetching in React components.

Installation

Install the package using npm or yarn:

npm install multi-api-fetcher

or

yarn add multi-api-fetcher

You'll also need to install @tanstack/react-query and axios if they are not already in your project:

npm install @tanstack/react-query axios

Requirements

  • React 16.8+ (for hooks support)
  • @tanstack/react-query and axios as peer dependencies

Usage

1. Wrap your app with QueryClientProvider

Before using useMultiApiFetcher, you need to wrap your React application with QueryClientProvider from TanStack Query to manage queries and caching.

import React from 'react';
import ReactDOM from 'react-dom';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import App from './App';

// Create a QueryClient instance
const queryClient = new QueryClient();

ReactDOM.render(
  <QueryClientProvider client={queryClient}>
    <App />
  </QueryClientProvider>,
  document.getElementById('root')
);

2. Using useMultiApiFetcher in Your Component

To fetch data from multiple APIs, use the useMultiApiFetcher hook. You need to pass an array of API objects, where each object contains:

  • key: A unique identifier for the API request.
  • url: The API endpoint from which you want to fetch data.

Example Usage:

import React from 'react';
import useMultiApiFetcher from 'multi-api-fetcher';

function App() {
  // Define the APIs to fetch from
  const apis = [
    { key: 'posts', url: 'https://jsonplaceholder.typicode.com/posts' },
    { key: 'users', url: 'https://jsonplaceholder.typicode.com/users' }
  ];

  // Fetch data from multiple APIs
  const results = useMultiApiFetcher(apis);

  // Check if any API is loading
  if (results.some(({ isLoading }) => isLoading)) {
    return <div>Loading...</div>;
  }

  // Check if any API has an error
  if (results.some(({ error }) => error)) {
    return <div>Error fetching data</div>;
  }

  // Display the fetched data
  return (
    <div>
      <h1>Posts</h1>
      <ul>
        {results[0].data.map(post => (
          <li key={post.id}>{post.title}</li>
        ))}
      </ul>

      <h1>Users</h1>
      <ul>
        {results[1].data.map(user => (
          <li key={user.id}>{user.name}</li>
        ))}
      </ul>
    </div>
  );
}

export default App;

Parameters for useMultiApiFetcher

const results = useMultiApiFetcher(apis);
  • apis (required): An array of objects, each representing an API request.
    • key (string): A unique key for the API request (used for caching and managing the request).
    • url (string): The API endpoint you want to fetch from.

Return Value

The useMultiApiFetcher hook returns an array of objects, where each object contains:

  • key: The unique identifier for the API request.
  • data: The data fetched from the API.
  • isLoading: A boolean indicating if the request is in the loading state.
  • error: Any error that occurred during the request.

Example:

const results = [
  {
    key: 'posts',
    data: [{ id: 1, title: 'Post 1' }, { id: 2, title: 'Post 2' }],
    isLoading: false,
    error: null,
  },
  {
    key: 'users',
    data: [{ id: 1, name: 'User 1' }, { id: 2, name: 'User 2' }],
    isLoading: false,
    error: null,
  },
];

Full Example with API Error Handling and Loading States

import React from 'react';
import useMultiApiFetcher from 'multi-api-fetcher';

const App = () => {
  const apis = [
    { key: 'posts', url: 'https://jsonplaceholder.typicode.com/posts' },
    { key: 'users', url: 'https://jsonplaceholder.typicode.com/users' }
  ];

  const results = useMultiApiFetcher(apis);

  // Combine loading and error states
  const isLoading = results.some(({ isLoading }) => isLoading);
  const isError = results.some(({ error }) => error);

  if (isLoading) {
    return <div>Loading...</div>;
  }

  if (isError) {
    return <div>Error fetching data</div>;
  }

  return (
    <div>
      <h1>Posts</h1>
      <ul>
        {results[0].data.map(post => (
          <li key={post.id}>{post.title}</li>
        ))}
      </ul>

      <h1>Users</h1>
      <ul>
        {results[1].data.map(user => (
          <li key={user.id}>{user.name}</li>
        ))}
      </ul>
    </div>
  );
};

export default App;

Error and Loading Handling

  • Loading: You can check if any of the API requests are still loading by using the .some function across the result set.
  • Error Handling: Similarly, you can check for errors and display appropriate error messages.
const isLoading = results.some(({ isLoading }) => isLoading);
const isError = results.some(({ error }) => error);

License

This package is licensed under the MIT License.

Contributing

Feel free to submit issues, feature requests, or contribute to the code via pull requests. Contributions and feedback are always welcome!


This package simplifies fetching data from multiple APIs using TanStack Query, making it easier to handle multiple loading states and errors in React applications.