Documentation

setQueryData

stable

Manually 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.

Core APIFunctional UpdatesOptimistic Updates

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

QueryKeyRequired

Unique identifier for the query. Can be a string or array of strings/numbers.

dataOrUpdater

TData | SetDataUpdater<TData>Required

New data to set directly, or an updater function that receives the previous data and returns the new data.

Returns

Returns

void

No return value

Examples

Direct Update

Set query data directly with a value

import { setQueryData } from 'qortex-react';
function handleUserUpdate() {
// Set user data directly
setQueryData(['user', 'current'], {
id: '123',
name: 'John Doe',
email: 'john@example.com'
});
// All components using this query will re-render with new data
console.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 fields
setQueryData('user', (prev) => ({
...prev,
name: 'Jane Doe'
}));
// Increment a counter
setQueryData('counter', (prev) => (prev ?? 0) + 1);
// Toggle a boolean
setQueryData('isOpen', (prev) => !prev);
// Add item to array
setQueryData('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 rollback
const currentPost = getQueryData(['post', postId]);
// Optimistically update using functional update
setQueryData(['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 error
if (currentPost) {
setQueryData(['post', postId], currentPost);
}
}
}

Array Operations

Add, remove, or update items in array data

import { setQueryData } from 'qortex-react';
// Add a new item
setQueryData('todos', (prev) => [
...(prev ?? []),
{ id: Date.now(), text: 'New todo', completed: false }
]);
// Remove an item by id
setQueryData('todos', (prev) =>
(prev ?? []).filter((todo) => todo.id !== targetId)
);
// Update an item
setQueryData('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 cache
setQueryData(['user', 'current'], undefined);
// Clear all user-related queries
setQueryData(['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