useFetch
TheuseFetch hook simplifies making asynchronous HTTP requests with built-in state management for loading, error handling, and data. It integrates with AniDev’s API service and provides automatic navigation for error states.
Type Signature
Parameters
The API endpoint URL to fetch data from
Optional fetch configuration options (headers, method, body, etc.)
When
true, the hook will not execute the fetch requestCallback function executed when the request succeeds
Callback function executed when the request fails
Automatically navigate to
/404 page when receiving a 404 responseHandle 403 forbidden responses (useful for parental controls)
Return Value
The fetched data of type T, or null if not yet loaded or on error
The HTTP status code of the response
Error object if the request failed, null otherwise
True while the request is in progress
Additional metadata from the API response
Total number of items (extracted from meta.total_items)
Function to manually trigger a new fetch request
Usage Examples
Basic Fetching
With Callbacks and Auto-Navigation
Conditional Fetching
Pagination Example
Use Cases
- Fetching anime lists with filtering and pagination
- Loading anime details with automatic 404 handling
- Search functionality with debounced queries
- User data with authentication checks (403 handling)
- Episode information for video playback
- Studio and genre data for filtering interfaces
Error Handling
The hook automatically maps HTTP status codes to appropriate error types:- 400: Validation error
- 401: Unauthorized error
- 403: Permission error (useful for parental controls)
- 404: Not found error
- 429: Rate limit error
- Other: Network error
The hook uses AniDev’s custom
AppError class for structured error handling, providing consistent error messages across the application.Dependencies
@libs/api- AniDev’s API client service@shared/errors- Custom error handling utilitiesastro:transitions/client- For programmatic navigation
Source
Location:src/domains/shared/hooks/useFetch.ts:16