react-get-post
v3.0.0
Published
A simple React hook for GETting and POSTing data
Readme
react-get-post
A lightweight and powerful React hook library for data fetching with GET and POST operations. Features built-in caching, loading states, error handling, optimistic updates, and race condition prevention.
Features
- 🚀 Simple & Intuitive - Easy-to-use hooks for common data fetching patterns
- 🎯 TypeScript Support - Full TypeScript support with proper type inference
- 💾 Built-in Caching - Automatic response caching across component instances
- ⚡ Optimistic Updates - Instant UI updates with automatic rollback on errors
- 🔄 Auto Retry - Intelligent retry logic for failed requests
- 🛡️ Race Condition Safe - Built-in epoch system prevents stale data updates
- 🎛️ Flexible Configuration - Customizable getter/poster functions and options
- 📦 Lightweight - Minimal dependencies, only requires React
Installation
npm install react-get-postQuick Start
Basic GET Request
import { useGet } from 'react-get-post'
function UserProfile({ userId }: { userId: string }) {
const { data, isGetting, error } = useGet<User>(`/api/users/${userId}`)
if (isGetting) return <div>Loading...</div>
if (error) return <div>Error: {error.message}</div>
return <div>Hello {data?.name}!</div>
}Basic POST Request
import { usePost } from 'react-get-post'
function CreateUser() {
const { isPosting, error, post } = usePost<Partial<User>, User>('/api/users', { getUrl: '/api/users' })
const handleSubmit = async (userData: Partial<User>) => {
await post(userData)
}
return (
<form onSubmit={handleSubmit}>
{/* form fields */}
<button disabled={isPosting}>
{isPosting ? 'Creating...' : 'Create User'}
</button>
{error && <div>Error: {error.message}</div>}
</form>
)
}API Reference
useGet<T>(url: string, options?: GetOptions)
Hook for GET requests with automatic caching and loading states.
Parameters
url- The endpoint URL to fetch fromoptions- Optional configuration object
Options
interface GetOptions {
getter?: (url: string) => Promise<T> // Custom fetch function
query?: Record<string, string> // Query parameters
keepPreviousData?: boolean // Maintain previous data while refetching
}Returns
{
data: T | null // The fetched data
isGetting: boolean // Loading state
error: Error | null // Error state
}Example
const { data, isGetting, error } = useGet<User[]>('/api/users', {
query: { page: '1', limit: '10' },
keepPreviousData: true
})usePost<TRequest, TResponse>(url: string, options?: PostOptions<TRequest, TResponse>)
Hook for POST requests with optimistic updates and automatic data synchronization.
Parameters
url- The endpoint URL to post tooptions- Optional configuration object
Options
interface PostOptions<TRequest, TResponse> {
poster?: (url: string, body: TRequest) => Promise<TResponse> // Custom post function
query?: Record<string, string> // Query parameters for POST
getUrl?: string // The GET endpoint to refresh/sync after successful POST
getterQuery?: Record<string, string> // Query parameters for GET refresh
optimisticData?: TResponse | ((value: TResponse, request?: TRequest) => TResponse) // Optimistic update data
useResponseData?: boolean // Use POST response for data update
}Returns
{
data: TResponse | null // Response data from POST
isPosting: boolean // Loading state
error: Error | null // Error state
post: (body: TRequest, extraOptions?: PostOptions<TRequest, TResponse>) => Promise<void> // Post function
}Example with Optimistic Updates
const { post, isPosting } = usePost<Partial<User>, User>('/api/users', {
getUrl: '/api/users',
optimisticData: (users: User[]) => [...users, newUser],
useResponseData: true
})
const handleCreate = async (userData: Partial<User>) => {
await post(userData)
}triggerGet(url: string, options?: GetOptions)
Manually trigger a GET request for a specific URL. Useful for refreshing data from outside components.
Example
import { triggerGet } from 'react-get-post'
// Refresh user data from anywhere in your app
triggerGet('/api/users', { query: { page: '1' } })Advanced Usage
Custom Fetch Functions
import { useGet, usePost } from 'react-get-post'
const customGetter = async (url: string) => {
const response = await fetch(url, {
headers: { 'Authorization': `Bearer ${token}` }
})
return response.json()
}
const { data } = useGet('/api/protected', { getter: customGetter })Optimistic Updates with Rollback
const { post } = usePost<Partial<Todo>, Todo>('/api/todos', {
getUrl: '/api/todos',
optimisticData: (todos: Todo[]) => [
...todos,
{ id: Date.now(), text: 'New todo', completed: false }
]
})
// If the POST fails, the optimistic update is automatically rolled back
await post({ text: 'New todo', completed: false })Data Persistence Across Components
// Component A
const { data } = useGet<User>('/api/user', { keepPreviousData: true })
// Component B (mounted later) - instantly gets cached data
const { data } = useGet<User>('/api/user', { keepPreviousData: true })Error Handling
The library includes built-in error handling and retry logic:
- Automatic Retry: Failed requests are automatically retried after 1 second if no data exists
- Race Condition Prevention: Epoch system ensures only the latest request updates the state
- Optimistic Rollback: Failed optimistic updates are automatically rolled back
TypeScript Support
Full TypeScript support with generic type parameters:
interface User {
id: number
name: string
email: string
}
const { data } = useGet<User>('/api/user/1') // data is typed as User | null
const { post } = usePost<Partial<User>, User>('/api/users', { getUrl: '/api/users' })Contributing
Contributions are welcome! Please feel free to submit a Pull Request.
License
MIT License - see the LICENSE.md file for details.
Author
stagas
- GitHub: @stagas
- Email: [email protected]
