or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

helpers.mdindex.mdmutations.mdplugin-setup.mdqueries.mdquery-client.mdstatus-utilities.md

query-client.mddocs/

0

# Query Client

1

2

Central management system for all query and mutation operations, providing cache control, data management, and global configuration for TanStack Vue Query.

3

4

## Capabilities

5

6

### QueryClient Class

7

8

Main client class for managing queries, mutations, and cache operations.

9

10

```typescript { .api }

11

/**

12

* Central client for managing all query and mutation operations

13

* @param config - Optional configuration for cache and default options

14

*/

15

class QueryClient {

16

constructor(config?: QueryClientConfig);

17

18

// Query data management

19

getQueryData<TData>(queryKey: QueryKey): TData | undefined;

20

setQueryData<TData>(

21

queryKey: QueryKey,

22

updater: Updater<TData | undefined, TData | undefined>,

23

options?: SetDataOptions

24

): TData | undefined;

25

getQueriesData<TData>(filters: QueryFilters): Array<[QueryKey, TData | undefined]>;

26

setQueriesData<TData>(

27

filters: QueryFilters,

28

updater: Updater<TData | undefined, TData | undefined>,

29

options?: SetDataOptions

30

): Array<[QueryKey, TData | undefined]>;

31

32

// Query state management

33

getQueryState<TData, TError>(queryKey: QueryKey): QueryState<TData, TError> | undefined;

34

35

// Cache operations

36

invalidateQueries(filters?: InvalidateQueryFilters, options?: InvalidateOptions): Promise<void>;

37

refetchQueries(filters?: RefetchQueryFilters, options?: RefetchOptions): Promise<void>;

38

cancelQueries(filters?: QueryFilters, options?: CancelOptions): Promise<void>;

39

removeQueries(filters?: QueryFilters): void;

40

resetQueries(filters?: QueryFilters, options?: ResetOptions): Promise<void>;

41

42

// Query execution

43

fetchQuery<TData>(options: FetchQueryOptions<TData>): Promise<TData>;

44

prefetchQuery<TData>(options: FetchQueryOptions<TData>): Promise<void>;

45

ensureQueryData<TData>(options: EnsureQueryDataOptions<TData>): Promise<TData>;

46

47

// Infinite query execution

48

fetchInfiniteQuery<TData, TPageParam>(

49

options: FetchInfiniteQueryOptions<TData, TPageParam>

50

): Promise<InfiniteData<TData, TPageParam>>;

51

prefetchInfiniteQuery<TData, TPageParam>(

52

options: FetchInfiniteQueryOptions<TData, TPageParam>

53

): Promise<void>;

54

55

// Status tracking

56

isFetching(filters?: QueryFilters): number;

57

isMutating(filters?: MutationFilters): number;

58

59

// Default options

60

setDefaultOptions(options: DefaultOptions): void;

61

getDefaultOptions(): DefaultOptions | undefined;

62

setQueryDefaults(queryKey: QueryKey, options: QueryObserverOptions): void;

63

getQueryDefaults(queryKey: QueryKey): QueryObserverOptions | undefined;

64

setMutationDefaults(mutationKey: MutationKey, options: MutationObserverOptions): void;

65

getMutationDefaults(mutationKey: MutationKey): MutationObserverOptions | undefined;

66

67

// Cache access

68

getQueryCache(): QueryCache;

69

getMutationCache(): MutationCache;

70

71

// Lifecycle

72

mount(): void;

73

unmount(): void;

74

clear(): void;

75

}

76

77

interface QueryClientConfig {

78

queryCache?: QueryCache;

79

mutationCache?: MutationCache;

80

defaultOptions?: DefaultOptions;

81

}

82

83

interface DefaultOptions {

84

queries?: QueryObserverOptions & ShallowOption;

85

mutations?: MutationObserverOptions & ShallowOption;

86

hydrate?: HydrateOptions['defaultOptions'];

87

dehydrate?: DehydrateOptions;

88

}

89

```

90

91

**Usage Examples:**

92

93

```typescript

94

import { QueryClient } from '@tanstack/vue-query';

95

96

// Basic client setup

97

const queryClient = new QueryClient();

98

99

// Client with custom configuration

100

const queryClient = new QueryClient({

101

defaultOptions: {

102

queries: {

103

staleTime: 1000 * 60 * 5, // 5 minutes

104

gcTime: 1000 * 60 * 30, // 30 minutes

105

retry: 3,

106

refetchOnWindowFocus: false,

107

},

108

mutations: {

109

retry: 1,

110

},

111

},

112

});

113

114

// Data management

115

const userData = queryClient.getQueryData(['user', userId]);

116

queryClient.setQueryData(['user', userId], (oldData) => ({

117

...oldData,

118

lastSeen: new Date().toISOString()

119

}));

120

121

// Cache operations

122

await queryClient.invalidateQueries({ queryKey: ['posts'] });

123

await queryClient.refetchQueries({ queryKey: ['user'] });

124

queryClient.removeQueries({ queryKey: ['temp'] });

125

126

// Prefetching

127

await queryClient.prefetchQuery({

128

queryKey: ['posts', 'popular'],

129

queryFn: () => fetch('/api/posts/popular').then(res => res.json()),

130

staleTime: 1000 * 60 * 10,

131

});

132

133

// Ensure data exists

134

const userData = await queryClient.ensureQueryData({

135

queryKey: ['user', userId],

136

queryFn: () => fetch(`/api/users/${userId}`).then(res => res.json()),

137

});

138

139

// Status checking

140

const fetchingCount = queryClient.isFetching();

141

const mutatingCount = queryClient.isMutating();

142

```

143

144

### useQueryClient

145

146

Composable to access the QueryClient instance within Vue components.

147

148

```typescript { .api }

149

/**

150

* Access the QueryClient instance via Vue's injection system

151

* @param id - Optional client ID for multi-client setups

152

* @returns QueryClient instance

153

* @throws Error if called outside setup() or no client found

154

*/

155

function useQueryClient(id?: string): QueryClient;

156

```

157

158

**Usage Examples:**

159

160

```typescript

161

import { useQueryClient } from '@tanstack/vue-query';

162

163

export default {

164

setup() {

165

const queryClient = useQueryClient();

166

167

const invalidateUserData = () => {

168

queryClient.invalidateQueries({ queryKey: ['user'] });

169

};

170

171

const prefetchUserPosts = async (userId) => {

172

await queryClient.prefetchQuery({

173

queryKey: ['posts', 'user', userId],

174

queryFn: () => fetch(`/api/users/${userId}/posts`).then(res => res.json())

175

});

176

};

177

178

return {

179

invalidateUserData,

180

prefetchUserPosts

181

};

182

}

183

};

184

```

185

186

### QueryCache & MutationCache

187

188

Cache classes for advanced cache management and event handling.

189

190

```typescript { .api }

191

/**

192

* Cache for storing and managing query data

193

*/

194

class QueryCache {

195

constructor(config?: QueryCacheConfig);

196

197

find<TData, TError>(filters: QueryFilters): Query<TData, TError> | undefined;

198

findAll(filters?: QueryFilters): Array<Query>;

199

subscribe(listener: QueryCacheNotifyEventListener): () => void;

200

clear(): void;

201

}

202

203

/**

204

* Cache for storing and managing mutation data

205

*/

206

class MutationCache {

207

constructor(config?: MutationCacheConfig);

208

209

find<TData, TError, TVariables, TContext>(

210

filters: MutationFilters

211

): Mutation<TData, TError, TVariables, TContext> | undefined;

212

findAll(filters?: MutationFilters): Array<Mutation>;

213

subscribe(listener: MutationCacheNotifyEventListener): () => void;

214

clear(): void;

215

}

216

217

interface QueryCacheConfig {

218

onError?: (error: unknown, query: Query<unknown, unknown>) => void;

219

onSuccess?: (data: unknown, query: Query<unknown, unknown>) => void;

220

onSettled?: (data: unknown | undefined, error: unknown | null, query: Query<unknown, unknown>) => void;

221

}

222

223

interface MutationCacheConfig {

224

onError?: (error: unknown, variables: unknown, context: unknown, mutation: Mutation<unknown, unknown, unknown, unknown>) => void;

225

onSuccess?: (data: unknown, variables: unknown, context: unknown, mutation: Mutation<unknown, unknown, unknown, unknown>) => void;

226

onSettled?: (data: unknown | undefined, error: unknown | null, variables: unknown, context: unknown, mutation: Mutation<unknown, unknown, unknown, unknown>) => void;

227

}

228

```

229

230

**Usage Examples:**

231

232

```typescript

233

import { QueryCache, MutationCache } from '@tanstack/vue-query';

234

235

// Custom cache with global error handling

236

const queryCache = new QueryCache({

237

onError: (error, query) => {

238

console.error('Query error:', error, 'Query key:', query.queryKey);

239

if (error.status === 401) {

240

// Handle authentication errors globally

241

router.push('/login');

242

}

243

}

244

});

245

246

const mutationCache = new MutationCache({

247

onError: (error) => {

248

console.error('Mutation error:', error);

249

// Show global error notification

250

showErrorToast(error.message);

251

}

252

});

253

254

const queryClient = new QueryClient({

255

queryCache,

256

mutationCache

257

});

258

259

// Subscribe to cache events

260

const unsubscribe = queryCache.subscribe((event) => {

261

if (event.type === 'added') {

262

console.log('Query added:', event.query.queryKey);

263

}

264

});

265

266

// Cleanup

267

onUnmounted(() => {

268

unsubscribe();

269

});

270

```

271

272

## Types

273

274

```typescript { .api }

275

// Core data types

276

type QueryKey = ReadonlyArray<unknown>;

277

type MutationKey = ReadonlyArray<unknown>;

278

279

// Updater function type

280

type Updater<TInput, TOutput> = TOutput | ((input: TInput) => TOutput);

281

282

// Query state interface

283

interface QueryState<TData = unknown, TError = DefaultError> {

284

data: TData | undefined;

285

dataUpdateCount: number;

286

dataUpdatedAt: number;

287

error: TError | null;

288

errorUpdateCount: number;

289

errorUpdatedAt: number;

290

fetchFailureCount: number;

291

fetchFailureReason: TError | null;

292

fetchMeta: FetchMeta | null;

293

isInvalidated: boolean;

294

status: QueryStatus;

295

fetchStatus: FetchStatus;

296

}

297

298

// Filter types

299

interface QueryFilters<TQueryFnData = unknown, TError = DefaultError, TData = TQueryFnData, TQueryKey extends QueryKey = QueryKey> {

300

exact?: boolean;

301

fetchStatus?: FetchStatus;

302

predicate?: (query: Query<TQueryFnData, TError, TData, TQueryKey>) => boolean;

303

queryKey?: TQueryKey;

304

stale?: boolean;

305

status?: QueryStatus;

306

type?: QueryTypeFilter;

307

}

308

309

interface MutationFilters {

310

exact?: boolean;

311

fetching?: boolean;

312

mutationKey?: MutationKey;

313

predicate?: (mutation: Mutation<any, any, any, any>) => boolean;

314

status?: MutationStatus;

315

}

316

317

// Options interfaces

318

interface SetDataOptions {

319

updatedAt?: number;

320

}

321

322

interface InvalidateOptions {

323

cancelRefetch?: boolean;

324

}

325

326

interface RefetchOptions {

327

cancelRefetch?: boolean;

328

}

329

330

interface CancelOptions {

331

revert?: boolean;

332

silent?: boolean;

333

}

334

335

interface ResetOptions {

336

cancelRefetch?: boolean;

337

}

338

339

// Fetch options

340

interface FetchQueryOptions<TQueryFnData, TError = DefaultError, TData = TQueryFnData, TQueryKey extends QueryKey = QueryKey> {

341

queryKey: TQueryKey;

342

queryFn?: QueryFunction<TQueryFnData, TQueryKey>;

343

staleTime?: number;

344

gcTime?: number;

345

retry?: boolean | number | ((failureCount: number, error: TError) => boolean);

346

retryDelay?: number | ((retryAttempt: number, error: TError) => number);

347

signal?: AbortSignal;

348

meta?: QueryMeta;

349

}

350

351

interface EnsureQueryDataOptions<TQueryFnData, TError = DefaultError, TData = TQueryFnData, TQueryKey extends QueryKey = QueryKey>

352

extends FetchQueryOptions<TQueryFnData, TError, TData, TQueryKey> {

353

revalidateIfStale?: boolean;

354

}

355

356

// Event listener types

357

type QueryCacheNotifyEventListener = (event: QueryCacheNotifyEvent) => void;

358

type MutationCacheNotifyEventListener = (event: MutationCacheNotifyEvent) => void;

359

360

interface QueryCacheNotifyEvent {

361

type: 'added' | 'removed' | 'updated';

362

query: Query<any, any, any, any>;

363

}

364

365

interface MutationCacheNotifyEvent {

366

type: 'added' | 'removed' | 'updated';

367

mutation: Mutation<any, any, any, any>;

368

}

369

```