Open History to see the last commit
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
25}
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: () =>
46 * console.log('Restoration completed successfully.'),
47 * }),
48 * ),
49 * ],
50 * }
51 * ```
52 *
53 * @param persistQueryClientOptions - Persistence options and optional onSuccess
54 * and onError callbacks which get called when the restoration process is
55 * complete.
56 * @returns A set of providers for use with `provideTanStackQuery`.
57 * @public
58 */
59export function withPersistQueryClient(
60 persistQueryClientOptions: PersistQueryClientOptions,
61): PersistQueryClientFeature {
62 const isRestoring = signal(true)
63 const providers = [
64 provideIsRestoring(isRestoring.asReadonly()),
65 {
66 // Do not use provideEnvironmentInitializer while Angular < v19 is supported
67 provide: ENVIRONMENT_INITIALIZER,
68 multi: true,
69 useValue: () => {
70 if (!isPlatformBrowser(inject(PLATFORM_ID))) return
71 const destroyRef = inject(DestroyRef)
72 const queryClient = inject(QueryClient)
73β
74 const { onSuccess, onError, persistOptions } = persistQueryClientOptions
75 const options = { queryClient, ...persistOptions }
76 persistQueryClientRestore(options)
77 .then(() => {
78 onSuccess?.()
79 })
80 .catch(() => {
81 onError?.()
82 })
83 .finally(() => {
84 isRestoring.set(false)
85 const cleanup = persistQueryClientSubscribe(options)
86 destroyRef.onDestroy(cleanup)
87 })
88 },
89 },
90 ]
91 return queryFeature('PersistQueryClient', providers)
92}