Documentation

setQueryData

stable

Manually 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

QueryKeyRequired

Unique identifier for the query. Can be a string, array, or object.

data

TDataRequired

New data to set for the query.

Returns

Returns

void

No return value

Examples

Basic Usage

Set query data directly

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');
}

Optimistic Updates

Update data optimistically before server response

import { setQueryData, getQueryData } from 'qortex-react';
function handleLikePost(postId: string) {
// Get current post data
const currentPost = getQueryData(['post', postId]);
if (currentPost) {
// Optimistically update the post data
setQueryData(['post', postId], {
...currentPost,
likes: currentPost.likes + 1,
liked: true
});
}
// Send the actual like request
fetch(`/api/posts/${postId}/like`, { method: 'POST' })
.then(() => {
// Server confirmed, data is already updated
console.log('Like successful');
})
.catch(() => {
// Revert the optimistic update on error
if (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 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

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