Skip to content
Source
Sign inSign up
TanStack/query
Open History to see the last commit

persistQueryClient.md

253 lines8.5 KB

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 ],
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
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()
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>
199```
200​
201Persisted Client entries have the following interface:
202​
203```ts
204export interface PersistedClient {
205 timestamp: number
206 buster: string
207 clientState: DehydratedState
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
248```
249​
250## Examples
251​
252- [Persister](../examples/basic-persister)
253- [SSR with persistence](../examples/ssr-persist)