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

swd-axios-queryv4

v1.0.5

Published

A React hooks library for easy API requests using Axios and React Query version 4

Downloads

38

Readme

SWD Axios Query v4

A React hooks library for easy API requests using Axios and React Query version 4. This package provides simplified, pre-configured hooks for common HTTP operations (GET, POST, PUT, DELETE) with built-in caching, error handling, and loading states.

✨ Features

  • 🚀 Simple API: Easy-to-use hooks for all HTTP methods
  • 🔄 Built-in Caching: Powered by React Query v4
  • Optimistic Updates: Automatic cache invalidation
  • 🛡️ Error Handling: Comprehensive error management
  • 🎯 TypeScript Ready: Full TypeScript support
  • 🔧 Configurable: Global and per-request configuration
  • 🎨 DevTools: Optional React Query DevTools integration

📦 Installation

npm install swd-axios-queryv4

Peer Dependencies

Make sure you have the required peer dependencies installed:

npm install react react-dom

🚀 Quick Start

1. Setup Provider

Wrap your app with the SWDQueryProvider:

import React from 'react';
import { SWDQueryProvider } from 'swd-axios-queryv4';
import App from './App';

function Root() {
  return (
    <SWDQueryProvider enableDevTools={process.env.NODE_ENV === 'development'}>
      <App />
    </SWDQueryProvider>
  );
}

export default Root;

2. Configure Base Settings

import { configureSWDQuery } from 'swd-axios-queryv4';

// Configure once in your app
configureSWDQuery({
  baseURL: 'https://api.example.com',
  headers: {
    'Content-Type': 'application/json',
    'Authorization': 'Bearer your-token'
  },
  defaultOptions: {
    retry: 1,
    refetchOnMount: true,
    refetchOnWindowFocus: false,
    networkMode: 'always'
  }
});

3. Use the Hooks

import React from 'react';
import { useGet, usePost, usePut, useDelete } from 'swd-axios-queryv4';

function UsersList() {
  // GET request
  const { data: users, isLoading, error } = useGet(['users'], '/users');
  
  // POST request
  const createUser = usePost(['users'], '/users', {
    onSuccess: (data) => {
      console.log('User created:', data);
    }
  });
  
  // PUT request
  const updateUser = usePut(['users'], '/users/1');
  
  // DELETE request
  const deleteUser = useDelete(['users'], '/users/1');

  if (isLoading) return <div>Loading...</div>;
  if (error) return <div>Error: {error.message}</div>;

  return (
    <div>
      <h1>Users</h1>
      {users?.map(user => (
        <div key={user.id}>{user.name}</div>
      ))}
      
      <button onClick={() => createUser.mutate({ name: 'John Doe' })}>
        Create User
      </button>
    </div>
  );
}

📚 API Reference

Hooks

useGet(queryKey, queryUrl, options)

Hook for GET requests with caching.

Parameters:

  • queryKey (Array): Unique key for caching
  • queryUrl (String): API endpoint
  • options (Object): React Query options

Returns:

  • data: Response data
  • isLoading: Loading state
  • error: Error object
  • refetch: Function to refetch data

Example:

const { data, isLoading, error, refetch } = useGet(
  ['posts', { page: 1 }], 
  '/posts?page=1',
  { enabled: true }
);

usePost(queryKey, queryUrl, options)

Hook for POST requests with automatic cache invalidation.

Parameters:

  • queryKey (Array): Cache key to invalidate after success
  • queryUrl (String): API endpoint
  • options (Object): Mutation options

Returns:

  • mutate: Function to trigger the request
  • mutateAsync: Async version of mutate
  • isLoading: Loading state
  • error: Error object
  • data: Response data

Example:

const createPost = usePost(['posts'], '/posts', {
  onSuccess: (data) => {
    console.log('Post created:', data);
  },
  onError: (error) => {
    console.error('Failed to create post:', error);
  }
});

// Trigger the request
createPost.mutate({ title: 'New Post', content: 'Post content' });

usePut(queryKey, queryUrl, options)

Hook for PUT requests with cache invalidation.

Example:

const updatePost = usePut(['posts'], '/posts/1');
updatePost.mutate({ title: 'Updated Title' });

useDelete(queryKey, queryUrl, options)

Hook for DELETE requests with cache invalidation.

Example:

const deletePost = useDelete(['posts'], '/posts/1');
deletePost.mutate();

Configuration

configureSWDQuery(config)

Global configuration for all requests.

configureSWDQuery({
  baseURL: 'https://api.example.com',
  headers: {
    'Authorization': 'Bearer token'
  },
  defaultOptions: {
    retry: 2,
    refetchOnMount: false,
    refetchOnWindowFocus: false,
    networkMode: 'always'
  }
});

addHeaders(headers)

Dynamically add headers to all future requests.

import { addHeaders } from 'swd-axios-queryv4';

// Add authentication header
addHeaders({
  'Authorization': `Bearer ${token}`
});

axiosInstance

Access the underlying Axios instance for custom configurations.

import { axiosInstance } from 'swd-axios-queryv4';

// Add request interceptor
axiosInstance.interceptors.request.use(config => {
  // Modify request config
  return config;
});

Provider Options

SWDQueryProvider

<SWDQueryProvider 
  queryClient={customQueryClient}  // Optional: Custom query client
  enableDevTools={true}            // Optional: Enable React Query DevTools
>
  <App />
</SWDQueryProvider>

🔧 Advanced Usage

Custom Query Client

import { QueryClient } from '@tanstack/react-query';
import { SWDQueryProvider } from 'swd-axios-queryv4';

const customQueryClient = new QueryClient({
  defaultOptions: {
    queries: {
      staleTime: 5 * 60 * 1000, // 5 minutes
      cacheTime: 10 * 60 * 1000, // 10 minutes
    },
  },
});

function App() {
  return (
    <SWDQueryProvider queryClient={customQueryClient}>
      {/* Your app */}
    </SWDQueryProvider>
  );
}

Error Handling

const { data, error } = useGet(['users'], '/users');

if (error) {
  // Handle different error types
  if (error.response?.status === 401) {
    // Handle unauthorized
  } else if (error.response?.status === 500) {
    // Handle server error
  }
}

Loading States

const { isLoading, isFetching } = useGet(['users'], '/users');
const createUser = usePost(['users'], '/users');

return (
  <div>
    {isLoading && <div>Initial loading...</div>}
    {isFetching && <div>Updating...</div>}
    
    <button 
      onClick={() => createUser.mutate(userData)}
      disabled={createUser.isLoading}
    >
      {createUser.isLoading ? 'Creating...' : 'Create User'}
    </button>
  </div>
);

🤝 Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

Development Setup

# Clone the repository
git clone <repository-url>

# Install dependencies
npm install

# Run linting
npm run lint

# Fix linting issues
npm run lint:fix

# Build the package
npm run build

📄 License

This project is licensed under the terms specified in the package.json file.

🐛 Issues

If you encounter any issues, please report them on the GitHub Issues page.

📈 Changelog

v1.0.4

  • Current stable version
  • React Query v4 support
  • Axios integration
  • Full TypeScript support

Made with ❤️ by William Antwi-Boasiako