useFilters
TheuseFilters hook manages job filtering, pagination, and API data fetching. It synchronizes filter state with URL parameters and handles loading states.
Location
/src/hooks/useFilters.js
Function Signature
Parameters
This hook takes no parameters.Return Value
Returns an object with the following properties:| Property | Type | Description |
|---|---|---|
jobs | Array | Array of job objects from the API |
loading | boolean | Loading state for API calls |
total | number | Total number of jobs matching filters |
totalPages | number | Total pages based on results per page (4) |
currentPage | number | Current active page number (1-indexed) |
textToFilter | string | Current text search query |
handlePageChange | function | Callback to change current page |
handleSearch | function | Callback to update filters |
handleTextFilter | function | Callback to update text search |
Usage Example
Fromsrc/pages/Search.jsx:
Handler Functions
handleSearch(filters)
Updates filter state and resets pagination to page 1. Parameters:handleTextFilter(text)
Updates the text search query and resets to page 1. Parameters:text(string): Search query text
handlePageChange(page)
Changes the current page number. Parameters:page(number): Target page number (1-indexed)
Internal State Management
The hook manages several pieces of state:Filter State
Text Filter State
Pagination State
API Data State
API Integration
The hook fetches data from the JSCamp API:text: Search querytechnology: Technology filtertype: Location filterlevel: Experience level filterlimit: Results per page (fixed at 4)offset: Pagination offset
URL Synchronization
The hook keeps URL parameters in sync with state:Pagination Calculation
Total pages is calculated based on total results:Best Practices
1. Reset Pagination on Filter Change
BothhandleSearch and handleTextFilter reset to page 1:
2. URL as Single Source of Truth
Initial state comes from URL parameters:- Shareable search URLs
- Browser back/forward navigation
- Page refresh without losing state
3. Loading States
Always show loading state during API calls:4. Error Handling
Log errors but don’t crash:Common Patterns
Combining with useSearchForm
Pass handlers to form components:Displaying Results Metadata
Related Hooks
- useSearchForm - Manages the search form UI
- useRouter - Handles navigation
Dependencies
react:useState,useEffectreact-router-dom:useSearchParams