swd-axios-queryv4
v1.0.5
Published
A React hooks library for easy API requests using Axios and React Query version 4
Downloads
38
Maintainers
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-queryv4Peer 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 cachingqueryUrl(String): API endpointoptions(Object): React Query options
Returns:
data: Response dataisLoading: Loading stateerror: Error objectrefetch: 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 successqueryUrl(String): API endpointoptions(Object): Mutation options
Returns:
mutate: Function to trigger the requestmutateAsync: Async version of mutateisLoading: Loading stateerror: Error objectdata: 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
