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

with-persist-query-client.ts

88 lines2.6 KB

1import {
2 QueryClient,
3 provideIsRestoring,
4 queryFeature,
5} from '@tanstack/angular-query-experimental'
6import {
7 DestroyRef,
8 ENVIRONMENT_INITIALIZER,
9 PLATFORM_ID,
10 inject,
11 signal,
12} from '@angular/core'
13import { isPlatformBrowser } from '@angular/common'
14import {
15 persistQueryClientRestore,
16 persistQueryClientSubscribe,
17} from '@tanstack/query-persist-client-core'
18import type { PersistQueryClientOptions as PersistQueryClientOptionsCore } from '@tanstack/query-persist-client-core'
19import type { PersistQueryClientFeature } from '@tanstack/angular-query-experimental'
20​
21type PersistQueryClientOptions = {
22 persistOptions: Omit<PersistQueryClientOptionsCore, 'queryClient'>
23 onSuccess?: () => Promise<unknown> | unknown
24 onError?: () => Promise<unknown> | unknown
26​
27/**
28 * Enables persistence.
29 *
30 * **Example**
31 *
32 * ```ts
33 * const localStoragePersister = createAsyncStoragePersister({
34 * storage: window.localStorage,
35 * })
36 *
37 * export const appConfig: ApplicationConfig = {
38 * providers: [
39 * provideTanStackQuery(
40 * new QueryClient(),
41 * withPersistQueryClient({
42 * persistOptions: {
43 * persister: localStoragePersister,
44 * },
45 * onSuccess: () => console.log('Restoration completed successfully.'),
46 * })
47 * ),
48 * ],
49 * };
50 * ```
51 * @param persistQueryClientOptions - persistence options and optional onSuccess and onError callbacks which get called when the restoration process is complete.
52 * @returns A set of providers for use with `provideTanStackQuery`.
53 * @public
54 */
55export function withPersistQueryClient(
56 persistQueryClientOptions: PersistQueryClientOptions,
57): PersistQueryClientFeature {
58 const isRestoring = signal(true)
59 const providers = [
60 provideIsRestoring(isRestoring.asReadonly()),
61 {
62 // Do not use provideEnvironmentInitializer while Angular < v19 is supported
63 provide: ENVIRONMENT_INITIALIZER,
64 multi: true,
65 useValue: () => {
66 if (!isPlatformBrowser(inject(PLATFORM_ID))) return
67 const destroyRef = inject(DestroyRef)
68 const queryClient = inject(QueryClient)
69​
70 const { onSuccess, onError, persistOptions } = persistQueryClientOptions
71 const options = { queryClient, ...persistOptions }
72 persistQueryClientRestore(options)
73 .then(() => {
74 onSuccess?.()
75 })
76 .catch(() => {
77 onError?.()
78 })
79 .finally(() => {
80 isRestoring.set(false)
81 const cleanup = persistQueryClientSubscribe(options)
82 destroyRef.onDestroy(cleanup)
83 })
84 },
85 },
86 ]
87 return queryFeature('PersistQueryClient', providers)