Open History to see the last commit
1---
2id: persistQueryClient
3title: persistQueryClient
4---
5β
6`@tanstack/angular-query-persist-client` saves your `QueryClient` cache with a **persister** and restores it the next time the application starts. Different persisters can store the cache in different storage layers.
7β
8## Installation
9β
10```sh
11npm install @tanstack/angular-query-persist-client
12```
13β
14or
15β
16```sh
17pnpm add @tanstack/angular-query-persist-client
18```
19β
20or
21β
22```sh
23yarn add @tanstack/angular-query-persist-client
24```
25β
26or
27β
28```sh
29bun add @tanstack/angular-query-persist-client
30```
31β
32You also need a persister. `@tanstack/query-async-storage-persister` and `@tanstack/query-sync-storage-persister` provide persisters for the Web Storage API and compatible stores, or you can [build your own](#persisters).
33β
34## Usage
35β
36Add `withPersistQueryClient` to `provideTanStackQuery`:
37β
38```ts
39import { QueryClient, provideTanStackQuery } from '@tanstack/angular-query'
40import { withPersistQueryClient } from '@tanstack/angular-query-persist-client'
41import { createAsyncStoragePersister } from '@tanstack/query-async-storage-persister'
42import type { ApplicationConfig } from '@angular/core'
43β
44export const appConfig: ApplicationConfig = {
45 providers: [
46 provideTanStackQuery(
47 () =>
48 new QueryClient({
49 defaultOptions: {
50 queries: {
51 gcTime: 24 * 60 * 60 * 1000, // 24 hours
52 },
53 },
54 }),
55 withPersistQueryClient(() => ({
56 persistOptions: {
57 persister: createAsyncStoragePersister({ storage: localStorage }),
58 },
59 })),
60 ),
61 ],
62}
63```
64β
65The options factory runs once per injector, in an injection context, and only in the browser. It can call `inject()` and use browser APIs such as `localStorage`. During server-side rendering the factory is not called and nothing is restored, so create persisters that access browser storage inside the factory.
66β
67When the injector is created in the browser, `withPersistQueryClient`:
68β
691. Restores the persisted cache into the `QueryClient`.
702. Subscribes to the query cache and saves changes through the persister.
713. Stops saving when the injector is destroyed.
72β
73Restoring is asynchronous. Queries do not start fetching while the cache is being restored. They still render, with `fetchStatus: 'idle'`, until the data has been restored. Then they refetch unless the restored data is fresh enough. `initialData` is respected.
74β
75### Options
76β
77The factory returns an object with:
78β
79- `persistOptions: PersistQueryClientOptions`
80 - all [options](#persistoptions) for persisting and restoring, minus the `QueryClient` itself
81- `onSuccess?: () => Promise<unknown> | unknown`
82 - optional
83 - will be called when the initial restore is finished
84 - can be used to [resumePausedMutations](../reference/classes/QueryClient.md#resumepausedmutations)
85 - if a Promise is returned, it will be awaited; restoring is seen as ongoing until then
86- `onError?: () => Promise<unknown> | unknown`
87 - optional
88 - will be called when an error is thrown during restoration
89 - if a Promise is returned, it will be awaited
90β
91### `persistOptions`
92β
93```ts
94interface PersistQueryClientOptions {
95 /** The Persister interface for storing and restoring the cache
96 * to/from a persisted location */
97 persister: Persister
98 /** The max-allowed age of the cache in milliseconds.
99 * If a persisted cache is found that is older than this
100 * time, it will be **silently** discarded
101 * (defaults to 24 hours) */
102 maxAge?: number
103 /** A unique string that can be used to forcefully
104 * invalidate existing caches if they do not share the same buster string */
105 buster?: string
106 /** The options passed to the hydrate function */
107 hydrateOptions?: HydrateOptions
108 /** The options passed to the dehydrate function */
109 dehydrateOptions?: DehydrateOptions
110}
111```
112β
113### injectIsRestoring
114β
115Use [`injectIsRestoring`](../reference/functions/injectIsRestoring.md) to check whether a restore is in progress. It returns a signal that is `true` while the cache is being restored. `injectQuery` and friends also check this internally to avoid race conditions between the restore and mounting queries.
116β
117```angular-ts
118import { Component } from '@angular/core'
119import { injectIsRestoring } from '@tanstack/angular-query'
120β
121@Component({
122 selector: 'app-root',
123 template: `
124 @if (isRestoring()) {
125 <p>Restoring the cache...</p>
126 }
127 `,
128})
129export class AppComponent {
130 readonly isRestoring = injectIsRestoring()
131}
132```
133β
134## How It Works
135β
136**IMPORTANT** - for persist to work properly, you probably want to pass `QueryClient` a `gcTime` value to override the default during hydration (as shown above).
137β
138If it is not set when creating the `QueryClient` instance, it will default to `300000` (5 minutes) for hydration, and the stored cache will be discarded after 5 minutes of inactivity. This is the default garbage collection behavior.
139β
140It should be set as the same value or higher than the `maxAge` option. E.g. if `maxAge` is 24 hours (the default) then `gcTime` should be 24 hours or higher. If lower than `maxAge`, garbage collection will kick in and discard the stored cache earlier than expected.
141β
142You can also pass it `Infinity` to disable garbage collection behavior entirely.
143β
144Due to a JavaScript limitation, the maximum allowed `gcTime` is about [24 days](https://developer.mozilla.org/en-US/docs/Web/API/setTimeout#maximum_delay_value), although it is possible to work around this limit using [timeoutManager.setTimeoutProvider](../reference/interfaces/TimeoutManager.md#settimeoutprovider).
145β
146### Cache Busting
147β
148Sometimes you may make changes to your application or data that immediately invalidate any and all cached data. If and when this happens, you can pass a `buster` string option. If the cache that is found does not also have that buster string, it will be discarded.
149β
150```ts
151withPersistQueryClient(() => ({
152 persistOptions: { persister, buster: buildHash },
153}))
154```
155β
156### Removal
157β
158If data is found to be any of the following:
159β
1601. expired (see `maxAge`)
1612. busted (see `buster`)
1623. error (ex: `throws ...`)
1634. empty (ex: `undefined`)
164β
165the persister `removeClient()` is called and the cache is immediately discarded.
166β
167## Persisters
168β
169### Storage persisters
170β
171`createAsyncStoragePersister` accepts any storage that adheres to the `AsyncStorage` interface. Storages that read and write synchronously, like `window.localStorage`, also adhere to it.
172β
173```ts
174import { createAsyncStoragePersister } from '@tanstack/query-async-storage-persister'
175β
176const persister = createAsyncStoragePersister({ storage: localStorage })
177```
178β
179`createSyncStoragePersister` accepts a synchronous storage, such as `window.localStorage` or `window.sessionStorage`.
180β
181```ts
182import { createSyncStoragePersister } from '@tanstack/query-sync-storage-persister'
183β
184const persister = createSyncStoragePersister({ storage: localStorage })
185```
186β
187Both throttle saving to happen at most every 1 second to save on potentially expensive writes.
188β
189### Persisters Interface
190β
191Persisters have the following interfaces:
192β
193```ts
194export interface Persister {
195 persistClient(persistClient: PersistedClient): Promisable<void>
196 restoreClient(): Promisable<PersistedClient | undefined>
197 removeClient(): Promisable<void>
198}
199```
200β
201Persisted Client entries have the following interface:
202β
203```ts
204export interface PersistedClient {
205 timestamp: number
206 buster: string
207 clientState: DehydratedState
208}
209```
210β
211You can import these (to build a persister):
212β
213```ts
214import {
215 PersistedClient,
216 Persister,
217} from '@tanstack/angular-query-persist-client'
218```
219β
220### Building A Persister
221β
222You can persist however you like. Here is an example of how to build an [Indexed DB](https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API) persister. Compared to `Web Storage API`, Indexed DB is faster, stores more than 5MB, and doesn't require serialization. That means it can readily store Javascript native types, such as `Date` and `File`.
223β
224```ts
225import {
226 PersistedClient,
227 Persister,
228} from '@tanstack/angular-query-persist-client'
229import { get, set, del } from 'idb-keyval'
230β
231/**
232 * Creates an Indexed DB persister
233 * @see https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API
234 */
235export function createIDBPersister(idbValidKey: IDBValidKey = 'angularQuery') {
236 return {
237 persistClient: async (client: PersistedClient) => {
238 await set(idbValidKey, client)
239 },
240 restoreClient: async () => {
241 return await get<PersistedClient>(idbValidKey)
242 },
243 removeClient: async () => {
244 await del(idbValidKey)
245 },
246 } satisfies Persister
247}
248```
249β
250## Examples
251β
252- [Persister](../examples/basic-persister)
253- [SSR with persistence](../examples/ssr-persist)