setQueryData
stableManually set query data
Manually set or update the cached data for a query. Useful for optimistic updates, cache invalidation, and programmatic data management.
Core APIOptimistic Updates
Optimistic Updates
setQueryData is perfect for optimistic updates. Update the UI immediately, then revert if the server request fails.
Signature
function setQueryData<TData>(queryKey: QueryKey,data: TData): void
Parameters
queryKey
QueryKeyRequiredUnique identifier for the query. Can be a string, array, or object.
data
TDataRequiredNew data to set for the query.
Returns
Returns
voidNo return value
Examples
Basic Usage
Set query data directly
import { setQueryData } from 'qortex-react';function handleUserUpdate() {// Set user data directlysetQueryData(['user', 'current'], {id: '123',name: 'John Doe',email: 'john@example.com'});// All components using this query will re-render with new dataconsole.log('User data updated');}
Optimistic Updates
Update data optimistically before server response
import { setQueryData, getQueryData } from 'qortex-react';function handleLikePost(postId: string) {// Get current post dataconst currentPost = getQueryData(['post', postId]);if (currentPost) {// Optimistically update the post datasetQueryData(['post', postId], {...currentPost,likes: currentPost.likes + 1,liked: true});}// Send the actual like requestfetch(`/api/posts/${postId}/like`, { method: 'POST' }).then(() => {// Server confirmed, data is already updatedconsole.log('Like successful');}).catch(() => {// Revert the optimistic update on errorif (currentPost) {setQueryData(['post', postId], {...currentPost,likes: currentPost.likes - 1,liked: false});}});}
Cache Invalidation
Clear or reset query data
import { setQueryData } from 'qortex-react';function handleLogout() {// Clear user data from cachesetQueryData(['user', 'current'], undefined);// Clear all user-related queriessetQueryData(['user', 'profile'], undefined);setQueryData(['user', 'settings'], undefined);console.log('User data cleared from cache');}
Behavior
Immediate Update
Updates cache immediately and triggers re-renders
Optimistic Updates
Perfect for optimistic UI updates before server confirmation
Cache Management
Allows manual cache manipulation and invalidation
Function Updates
Supports functional updates for complex state changes
Best Practices
Do's
- ✓Use for optimistic updates in user interactions
- ✓Use functional updates for complex state changes
- ✓Handle error cases by reverting optimistic updates
- ✓Use for cache invalidation and cleanup
Don'ts
- ✗Don't use for initial data loading (use fetchQuery instead)
- ✗Don't forget to handle error cases in optimistic updates
- ✗Don't mutate the data object directly
- ✗Don't use without understanding the impact on components