invalidateQuery
stableInvalidate and refetch a query
Mark a query as stale and trigger a refetch. Useful for refreshing data after mutations or when you know the data is outdated.
Post-Mutation Invalidation
invalidateQuery is commonly used after mutations to ensure related data is refreshed and up-to-date.
Performance Consideration
Invalidating queries triggers refetches. Be mindful of the impact on performance and network usage.
Signature
function invalidateQuery(queryKey: QueryKey): void
Parameters
queryKey
QueryKeyRequiredUnique identifier for the query. Can be a string, array, or object.
Returns
Returns
voidNo return value. Invalidation is synchronous, but triggers async refetch.
Examples
Basic Usage
Invalidate and refetch a query
import { invalidateQuery } from 'qortex-react';function RefreshButton() {const handleRefresh = () => {// Invalidate and refetch user data (synchronous)invalidateQuery(['user', 'current']);console.log('User data refresh triggered');};return (<button onClick={handleRefresh}>Refresh User Data</button>);}
After Mutation
Invalidate related queries after a mutation
import { invalidateQuery } from 'qortex-react';async function handleCreatePost(postData: any) {try {// Create the postconst response = await fetch('/api/posts', {method: 'POST',body: JSON.stringify(postData)});if (response.ok) {// Invalidate posts list to refetch with new postinvalidateQuery('posts');// Invalidate user posts if it existsinvalidateQuery(['user', 'posts']);console.log('Post created and cache invalidated');}} catch (error) {console.error('Failed to create post:', error);}}
Bulk Invalidation
Invalidate multiple related queries
import { invalidateQuery } from 'qortex-react';async function handleUserUpdate(userId: string) {try {// Update user dataawait fetch(`/api/users/${userId}`, {method: 'PUT',body: JSON.stringify(userData)});// Invalidate all user-related queriesconst queriesToInvalidate = [['user', userId],['user', 'current'],['user', 'profile'],['user', 'settings']];queriesToInvalidate.forEach(queryKey => invalidateQuery(queryKey));console.log('All user queries invalidated');} catch (error) {console.error('Failed to update user:', error);}}
Behavior
Stale Marking
Marks the query as stale, triggering a refetch
Automatic Refetch
Automatically refetches data if components are subscribed
Promise-based
Returns a Promise for async/await usage
Cache Integration
Works seamlessly with the query cache system
Best Practices
Do's
- ✓Use after mutations to refresh related data
- ✓Use for manual refresh functionality
- ✓Invalidate related queries together
- ✓Handle errors appropriately
Don'ts
- ✗Don't use for initial data loading
- ✗Don't invalidate too frequently
- ✗Don't forget to handle Promise rejections
- ✗Don't use without understanding the impact on performance