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

with-persist-query-client.ts

83 lines2.5 KB

1import { QueryClient } from '@tanstack/angular-query'
2import {
3 DestroyRef,
4 InjectionToken,
5 PLATFORM_ID,
6 inject,
7 makeEnvironmentProviders,
8 provideEnvironmentInitializer,
9 signal,
10} from '@angular/core'
11import {
12 provideIsRestoring,
13 queryFeature,
14} from '@tanstack/angular-query/internal'
15import { isPlatformBrowser } from '@angular/common'
16import {
17 persistQueryClientRestore,
18 persistQueryClientSubscribe,
19} from '@tanstack/query-persist-client-core'
20import type { WritableSignal } from '@angular/core'
21import type { QueryFeature } from '@tanstack/angular-query'
22import type { WithPersistQueryClientFn } from './with-persist-query-client.types'
23​
24const RESTORING_STATE = new InjectionToken<WritableSignal<boolean>>(
25 'Query restoration state',
27​
28export type {
29 PersistQueryClientUserOptions,
30 WithPersistQueryClientFn,
31} from './with-persist-query-client.types'
32​
33/**
34 * Enables persistence. The options factory runs once per injector, only in the
35 * browser, in an Angular injection context. It can call `inject()` and use
36 * browser APIs such as `localStorage`.
37 *
38 * ```ts
39 * withPersistQueryClient(() => ({
40 * persistOptions: {
41 * persister: createAsyncStoragePersister({ storage: localStorage }),
42 * },
43 * }))
44 * ```
45 * @param optionsFactory - Creates the persistence options in the browser.
46 * @returns A set of providers for use with `provideTanStackQuery`.
47 * @public
48 */
49export function withPersistQueryClient(
50 optionsFactory: WithPersistQueryClientFn,
51): QueryFeature {
52 return queryFeature(
53 makeEnvironmentProviders([
54 { provide: RESTORING_STATE, useFactory: () => signal(true) },
55 provideIsRestoring(() => inject(RESTORING_STATE).asReadonly()),
56 provideEnvironmentInitializer(() => {
57 const isRestoring = inject(RESTORING_STATE)
58 if (!isPlatformBrowser(inject(PLATFORM_ID))) {
59 isRestoring.set(false)
60 return
61 }
62 const destroyRef = inject(DestroyRef)
63 const queryClient = inject(QueryClient)
64​
65 const { onSuccess, onError, persistOptions } = optionsFactory()
66 const options = { queryClient, ...persistOptions }
67 void persistQueryClientRestore(options)
68 .then(() => {
69 return onSuccess?.()
70 })
71 .catch(() => {
72 return onError?.()
73 })
74 .finally(() => {
75 if (destroyRef.destroyed) return
76 isRestoring.set(false)
77 const cleanup = persistQueryClientSubscribe(options)
78 destroyRef.onDestroy(cleanup)
79 })
80 }),
81 ]),
82 )