CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-tanstack--query-core

The framework agnostic core that powers TanStack Query for data fetching and caching

Pending
Overview
Eval results
Files

client-management.mddocs/

Client Management

Central client orchestration system for managing all query and mutation operations with intelligent defaults, caching strategies, and comprehensive lifecycle management.

Capabilities

QueryClient

The main client class that orchestrates all query and mutation operations.

/**
 * Central client for managing queries and mutations
 * Provides configuration, lifecycle management, and cache access
 */
class QueryClient {
  constructor(config?: QueryClientConfig);
  
  // Lifecycle management
  mount(): void;
  unmount(): void;
  clear(): void;
  
  // Cache access
  getQueryCache(): QueryCache;
  getMutationCache(): MutationCache;
  
  // Query data operations
  getQueryData<T>(queryKey: QueryKey): T | undefined;
  setQueryData<T>(queryKey: QueryKey, updater: Updater<T>, options?: SetDataOptions): T | undefined;
  getQueriesData<T>(filters: QueryFilters): Array<[QueryKey, T | undefined]>;
  setQueriesData<T>(filters: QueryFilters, updater: Updater<T>, options?: SetDataOptions): Array<[QueryKey, T | undefined]>;
  getQueryState<T>(queryKey: QueryKey): QueryState<T> | undefined;
  
  // Query operations
  ensureQueryData<T>(options: EnsureQueryDataOptions<T>): Promise<T>;
  ensureInfiniteQueryData<T>(options: EnsureInfiniteQueryDataOptions<T>): Promise<InfiniteData<T>>;
  fetchQuery<T>(options: FetchQueryOptions<T>): Promise<T>;
  prefetchQuery<T>(options: FetchQueryOptions<T>): Promise<void>;
  fetchInfiniteQuery<T>(options: FetchInfiniteQueryOptions<T>): Promise<InfiniteData<T>>;
  prefetchInfiniteQuery<T>(options: FetchInfiniteQueryOptions<T>): Promise<void>;
  
  // Query lifecycle
  invalidateQueries(filters?: InvalidateQueryFilters, options?: InvalidateOptions): Promise<void>;
  refetchQueries(filters?: RefetchQueryFilters, options?: RefetchOptions): Promise<void>;
  cancelQueries(filters?: QueryFilters, options?: CancelOptions): Promise<void>;
  removeQueries(filters?: QueryFilters): void;
  resetQueries(filters?: QueryFilters, options?: ResetOptions): Promise<void>;
  
  // Configuration
  getDefaultOptions(): DefaultOptions;
  setDefaultOptions(options: DefaultOptions): void;
  setQueryDefaults(queryKey: QueryKey, options: Partial<QueryObserverOptions>): void;
  getQueryDefaults(queryKey: QueryKey): Partial<QueryObserverOptions>;
  setMutationDefaults(mutationKey: MutationKey, options: Partial<MutationObserverOptions>): void;
  getMutationDefaults(mutationKey: MutationKey): Partial<MutationObserverOptions>;
  
  // Status queries
  isFetching(filters?: QueryFilters): number;
  isMutating(filters?: MutationFilters): number;
  
  // Mutations
  resumePausedMutations(): Promise<unknown>;
}

interface QueryClientConfig {
  queryCache?: QueryCache;
  mutationCache?: MutationCache;
  defaultOptions?: DefaultOptions;
}

interface DefaultOptions {
  queries?: Partial<QueryObserverOptions>;
  mutations?: Partial<MutationObserverOptions>;
}

interface SetDataOptions {
  updatedAt?: number;
}

Usage Examples:

import { QueryClient } from "@tanstack/query-core";

// Basic client setup
const queryClient = new QueryClient();

// Client with custom configuration
const queryClient = new QueryClient({
  defaultOptions: {
    queries: {
      staleTime: 5 * 60 * 1000, // 5 minutes
      gcTime: 10 * 60 * 1000,   // 10 minutes
      retry: 3,
    },
    mutations: {
      retry: 1,
    },
  },
});

// Mount client (in frameworks)
queryClient.mount();

// Get cached data
const userData = queryClient.getQueryData(['user', 123]);

// Set cached data
queryClient.setQueryData(['user', 123], (oldData) => ({
  ...oldData,
  name: 'Updated Name',
}));

// Fetch data imperatively
const user = await queryClient.fetchQuery({
  queryKey: ['user', 123],
  queryFn: async () => {
    const response = await fetch('/api/user/123');
    return response.json();
  },
});

// Invalidate and refetch queries
await queryClient.invalidateQueries({
  queryKey: ['user'],
});

// Cleanup
queryClient.unmount();

Lifecycle Management

Methods for managing the client lifecycle and cleanup.

/**
 * Mount the client and set up subscriptions
 * Should be called when the client is first used
 */
mount(): void;

/**
 * Unmount the client and cleanup subscriptions
 * Should be called when the client is no longer needed
 */
unmount(): void;

/**
 * Clear all queries and mutations from caches
 * Removes all cached data and resets state
 */
clear(): void;

Data Access Methods

Direct access to cached query data with type safety.

/**
 * Get cached data for a specific query
 * @param queryKey - The query key to retrieve data for
 * @returns The cached data or undefined if not found
 */
getQueryData<T>(queryKey: QueryKey): T | undefined;

/**
 * Set or update cached data for a specific query
 * @param queryKey - The query key to set data for
 * @param updater - New data or function to update existing data
 * @param options - Additional options for setting data
 * @returns The updated data
 */
setQueryData<T>(
  queryKey: QueryKey,
  updater: Updater<T>,
  options?: SetDataOptions
): T | undefined;

/**
 * Get cached data for multiple queries matching filters
 * @param filters - Query filters to match against
 * @returns Array of [queryKey, data] tuples
 */
getQueriesData<T>(filters: QueryFilters): Array<[QueryKey, T | undefined]>;

/**
 * Set cached data for multiple queries matching filters
 * @param filters - Query filters to match against
 * @param updater - New data or function to update existing data
 * @param options - Additional options for setting data
 * @returns Array of [queryKey, data] tuples
 */
setQueriesData<T>(
  filters: QueryFilters,
  updater: Updater<T>,
  options?: SetDataOptions
): Array<[QueryKey, T | undefined]>;

/**
 * Get the complete state for a specific query
 * @param queryKey - The query key to get state for
 * @returns The query state or undefined if not found
 */
getQueryState<T>(queryKey: QueryKey): QueryState<T> | undefined;

Configuration Management

Methods for managing default options and query-specific defaults.

/**
 * Get current default options for queries and mutations
 * @returns Current default options
 */
getDefaultOptions(): DefaultOptions;

/**
 * Set default options for all queries and mutations
 * @param options - New default options to merge
 */
setDefaultOptions(options: DefaultOptions): void;

/**
 * Set default options for queries matching a specific key
 * @param queryKey - Query key pattern to set defaults for
 * @param options - Default options for matching queries
 */
setQueryDefaults(queryKey: QueryKey, options: Partial<QueryObserverOptions>): void;

/**
 * Get default options for queries matching a specific key
 * @param queryKey - Query key pattern to get defaults for
 * @returns Default options for matching queries
 */
getQueryDefaults(queryKey: QueryKey): Partial<QueryObserverOptions>;

/**
 * Set default options for mutations matching a specific key
 * @param mutationKey - Mutation key pattern to set defaults for
 * @param options - Default options for matching mutations
 */
setMutationDefaults(mutationKey: MutationKey, options: Partial<MutationObserverOptions>): void;

/**
 * Get default options for mutations matching a specific key
 * @param mutationKey - Mutation key pattern to get defaults for
 * @returns Default options for matching mutations
 */
getMutationDefaults(mutationKey: MutationKey): Partial<MutationObserverOptions>;

Status Queries

Methods for checking the status of queries and mutations.

/**
 * Count the number of queries currently fetching
 * @param filters - Optional filters to narrow the count
 * @returns Number of fetching queries
 */
isFetching(filters?: QueryFilters): number;

/**
 * Count the number of mutations currently pending
 * @param filters - Optional filters to narrow the count
 * @returns Number of pending mutations
 */
isMutating(filters?: MutationFilters): number;

Types

interface QueryState<TData = unknown, TError = Error> {
  data: TData | undefined;
  dataUpdateCount: number;
  dataUpdatedAt: number;
  error: TError | null;
  errorUpdateCount: number;
  errorUpdatedAt: number;
  fetchFailureCount: number;
  fetchFailureReason: TError | null;
  fetchMeta: FetchMeta | null;
  isInvalidated: boolean;
  status: QueryStatus;
  fetchStatus: FetchStatus;
}

type MutationKey = ReadonlyArray<unknown>;

interface EnsureQueryDataOptions<T> extends FetchQueryOptions<T> {
  revalidateIfStale?: boolean;
}

interface EnsureInfiniteQueryDataOptions<T> extends FetchInfiniteQueryOptions<T> {
  revalidateIfStale?: boolean;
}

interface InvalidateOptions {
  refetchType?: 'active' | 'inactive' | 'all' | 'none';
}

interface RefetchOptions extends CancelOptions {
  throwOnError?: boolean;
}

interface CancelOptions {
  revert?: boolean;
  silent?: boolean;
}

interface ResetOptions extends RefetchOptions {}

Install with Tessl CLI

npx tessl i tessl/npm-tanstack--query-core

docs

browser-integration.md

cache-management.md

client-management.md

hydration.md

index.md

infinite-queries.md

mutations.md

query-observers.md

query-operations.md

utilities.md

tile.json