setQueryData
stableManually set query data
Manually set or update the cached data for a query. Supports both direct values and updater functions for accessing previous data. Useful for optimistic updates, cache invalidation, and programmatic data management.
Functional Updates
Use the updater function pattern when you need to base the new state on the previous value. This is safer than reading and then writing, as it avoids race conditions.
Handle Undefined
The previous value in updater functions can be undefined. Always handle this case: (prev) => (prev ?? defaultValue) + 1
Signature
function setQueryData<TData>(queryKey: QueryKey,dataOrUpdater: TData | ((prev: TData | undefined) => TData)): void
Parameters
queryKey
QueryKeyRequiredUnique identifier for the query. Can be a string or array of strings/numbers.
dataOrUpdater
TData | SetDataUpdater<TData>RequiredNew data to set directly, or an updater function that receives the previous data and returns the new data.
Returns
Returns
voidNo return value
Examples
Direct Update
Set query data directly with a value
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');}
Functional Update
Use an updater function to access previous data
import { setQueryData } from 'qortex-react';// Update user name while preserving other fieldssetQueryData('user', (prev) => ({...prev,name: 'Jane Doe'}));// Increment a countersetQueryData('counter', (prev) => (prev ?? 0) + 1);// Toggle a booleansetQueryData('isOpen', (prev) => !prev);// Add item to arraysetQueryData('todos', (prev) => [...(prev ?? []),{ id: Date.now(), text: 'New todo' }]);
Optimistic Updates
Update data optimistically before server response
import { setQueryData, getQueryData } from 'qortex-react';async function handleLikePost(postId: string) {// Get current post data for rollbackconst currentPost = getQueryData(['post', postId]);// Optimistically update using functional updatesetQueryData(['post', postId], (prev) => ({...prev,likes: (prev?.likes ?? 0) + 1,liked: true}));try {await fetch(`/api/posts/${postId}/like`, { method: 'POST' });console.log('Like successful');} catch {// Revert the optimistic update on errorif (currentPost) {setQueryData(['post', postId], currentPost);}}}
Array Operations
Add, remove, or update items in array data
import { setQueryData } from 'qortex-react';// Add a new itemsetQueryData('todos', (prev) => [...(prev ?? []),{ id: Date.now(), text: 'New todo', completed: false }]);// Remove an item by idsetQueryData('todos', (prev) =>(prev ?? []).filter((todo) => todo.id !== targetId));// Update an itemsetQueryData('todos', (prev) =>(prev ?? []).map((todo) =>todo.id === targetId ? { ...todo, completed: true } : todo));
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
Functional Updates
Pass a function to access previous data: (prev) => newData
Optimistic Updates
Perfect for optimistic UI updates before server confirmation
Equality Check
Skips update if new data equals previous (configurable via equalityStrategy)
Best Practices
Do's
- ✓Use functional updates when you need access to previous data
- ✓Use for optimistic updates in user interactions
- ✓Handle null/undefined in updater functions: (prev ?? defaultValue)
- ✓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 previous data object directly in updater
- ✗Don't use without understanding the impact on components