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 🙏

© 2026 – Pkg Stats / Ryan Hefner

@acxxsdpj/libra-query

v1.0.0

Published

A React Query wrapper library for HTTP requests with Axios

Downloads

64

Readme

libra-query

A React Query wrapper library for HTTP requests with Axios, providing a type-safe and easy-to-use API for data fetching and mutations in React applications.

Features

  • Type-safe: Built with TypeScript for full type safety
  • React Query Integration: Leverages the power of React Query for caching, refetching, and state management
  • Request Builder Pattern: Fluent API for building HTTP requests
  • Flexible Configuration: Support for custom headers, interceptors, and request options
  • Multiple HTTP Methods: Built-in support for GET, POST, PUT, DELETE, etc.
  • Automatic Query Keys: Smart query key generation for optimal caching

Installation

pnpm add libra-query
# or
npm install libra-query
# or
yarn add libra-query

Peer Dependencies

This package requires the following peer dependencies:

{
  "react": "^18.0.0",
  "@tanstack/react-query": "^5.0.0"
}

Quick Start

1. Wrap your app with the provider

import { LibraQueryProvider } from 'libra-query/provider';

function App() {
  return (
    <LibraQueryProvider
      baseURL="https://api.example.com"
      timeout={30000}
      headers={{
        'X-Custom-Header': 'value',
      }}
      requestInterceptor={(config) => {
        // Modify request config before sending
        console.log('Request:', config);
        return config;
      }}
      responseInterceptor={(response) => {
        // Modify response data
        console.log('Response:', response);
        return response;
      }}
    >
      {/* Your app components */}
    </LibraQueryProvider>
  );
}

2. Set up the request builder

import { RequestBuilder } from 'libra-query/builder';
import { useLibraQuery } from 'libra-query/provider';

// Define your API endpoints
export const getUserApi = new RequestBuilder({
  url: '/api/user',
  method: 'get',
});

export const updateUserApi = new RequestBuilder({
  url: '/api/user',
  method: 'put',
});

3. Use in your components

import { useMemo } from 'react';
import { getUserApi, updateUserApi } from './api';
import { useLibraQuery } from 'libra-query/provider';

function UserProfile() {
  const { requestInstance } = useLibraQuery();

  // Configure the request builder to use the provider's request instance
  const userApi = useMemo(() => new RequestBuilder({
    url: '/api/user',
    method: 'get',
    requestFn: requestInstance,
  }), [requestInstance]);

  // Fetch data with useQuery
  const { data: user, isLoading, error } = userApi.useQuery();

  // Update data with useMutation
  const updateMutation = updateUserApi.useMutation({
    onSuccess: () => {
      console.log('User updated successfully');
    },
  });

  if (isLoading) return <div>Loading...</div>;
  if (error) return <div>Error loading user</div>;

  return (
    <div>
      <h1>{user?.name}</h1>
      <button onClick={() => updateMutation.mutate({ name: 'New Name' })}>
        Update Name
      </button>
    </div>
  );
}

API Reference

LibraQueryProvider

Provider component that wraps your app with React Query and provides a configured Axios instance.

Props

interface LibraQueryConfig {
  baseURL?: string;           // Base URL for all API requests
  timeout?: number;           // Request timeout in milliseconds (default: 30000)
  headers?: RawAxiosRequestHeaders;  // Custom headers to include in all requests
  requestInterceptor?: (config) => config | Promise<config>;  // Request interceptor
  responseInterceptor?: (response) => response | Promise<response>;  // Response interceptor
  responseErrorInterceptor?: (error) => any | Promise<any>;  // Error interceptor
  silence?: boolean;          // Disable automatic error messages (default: false)
}

Example

<LibraQueryProvider
  baseURL="https://api.example.com"
  headers={{
    'Authorization': 'Bearer token',
    'X-Custom-Header': 'value',
  }}
  requestInterceptor={(config) => {
    console.log('Sending request:', config);
    return config;
  }}
  responseInterceptor={(response) => {
    console.log('Received response:', response);
    return response;
  }}
>
  <App />
</LibraQueryProvider>

useLibraQuery

Hook to access the request instance and configuration from the LibraQueryProvider.

function MyComponent() {
  const { requestInstance, config } = useLibraQuery();

  // Use requestInstance with RequestBuilder
  const api = useMemo(() => new RequestBuilder({
    url: '/endpoint',
    requestFn: requestInstance,
  }), [requestInstance]);

  // ...
}

RequestBuilder

The core class for building API requests.

Constructor Options

interface RequestBuilderOptions<Req, Res> {
  method?: Lowercase<Method>; // HTTP method, default: 'get'
  url: string;                // API endpoint URL
  urlPathParams?: string[];   // Path parameters, e.g., ['id'] for '/api/user/{id}'
  requestFn?: <T>(config: AxiosRequestConfig) => Promise<T>;
  meta?: RequestBuilderMeta;
  useQueryOptions?: UseQueryOptions<Res, Error, Res>;
  useMutationOptions?: UseMutationOptions<Res, Error, Req>;
}

Methods

request(params?, config?)

Make a direct HTTP request.

const data = await api.request({ userId: 123 });
useQuery(params?, options?)

React Query hook for fetching data.

const { data, isLoading, error } = api.useQuery(
  { page: 1 },
  {
    staleTime: 60000,
  }
);
useMutation(options?)

React Query hook for mutations.

const mutation = api.useMutation({
  onSuccess: (data) => {
    console.log('Success:', data);
  },
});

mutation.mutate({ name: 'John' });

ReactQueryProvider

Legacy provider component (use LibraQueryProvider instead for full functionality).

import { ReactQueryProvider } from 'libra-query/provider';

<ReactQueryProvider>{children}</ReactQueryProvider>

Default Configuration

The default configuration includes:

  • Stale Time: 5 minutes
  • Retry: 1 retry on failure
  • Refetch on Window Focus: Disabled
  • Refetch on Reconnect: Enabled

Custom Request Function

You can create custom request instances:

import { getRequestFn } from 'libra-query';
import { RequestBuilder } from 'libra-query/builder';

const customRequest = getRequestFn({
  prefix: 'https://api.example.com',
  requestInterceptor: (config) => {
    // Modify request config
    config.headers = {
      ...config.headers,
      'X-Custom-Header': 'value',
    };
    return config;
  },
  silence: false,
});

const api = new RequestBuilder({
  url: '/endpoint',
  requestFn: customRequest,
});

License

MIT