Basic Query Function
A query function must return a promise that resolves data or throws an error:Query functions must throw errors instead of returning them for proper error handling.
Query Function Context
Query functions receive a context object with useful properties:Using the Context
Query Function Patterns
- Inline Function
- Separate Function
- With Parameters
- From Query Key
Handling Errors
Query functions should throw errors for failed requests:Query Function with Axios
Query Function with Fetch API
Complete example with proper error handling:Cancellation with AbortSignal
Use the signal for request cancellation:When a query is cancelled (e.g., component unmounts), the AbortSignal is automatically triggered.
Dependent Data in Query Functions
Extract dependencies from the query key:Parallel Requests in Query Function
Fetch multiple resources in a single query:Default Query Function
Set a default query function for all queries:TypeScript Query Functions
Type-safe query functions:Query Functions with GraphQL
Query Functions with tRPC
Paginated Query Function
Infinite Query Function
Query Function Error Types
Type errors properly:Retry Logic in Query Functions
Query functions automatically retry based on query options:The query function doesn’t need to implement retry logic - TanStack Query handles it automatically.
Query Function with Authentication
Transforming Data in Query Functions
Query Function Best Practices
1
Always Return Promises
Query functions must return a promise.
2
Throw Errors
Throw errors instead of returning them.
3
Use AbortSignal
Support cancellation with the signal.
4
Extract from Query Key
Get parameters from the query key for consistency.