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

create-base-query.ts

85 lines2.4 KB

1import {
2 DestroyRef,
3 assertInInjectionContext,
4 computed,
5 effect,
6 inject,
7 signal,
8} from '@angular/core'
9import { notifyManager } from '@tanstack/query-core'
10import { signalProxy } from './signal-proxy'
11import type { QueryClient, QueryKey, QueryObserver } from '@tanstack/query-core'
12import type { CreateBaseQueryOptions, CreateBaseQueryResult } from './types'
13​
14/**
15 * Base implementation for `injectQuery` and `injectInfiniteQuery`.
16 */
17export function createBaseQuery<
18 TQueryFnData,
19 TError,
20 TData,
21 TQueryData,
22 TQueryKey extends QueryKey,
23>(
24 options: (
25 client: QueryClient,
26 ) => CreateBaseQueryOptions<
27 TQueryFnData,
28 TError,
29 TData,
30 TQueryData,
31 TQueryKey
32 >,
33 Observer: typeof QueryObserver,
34 queryClient: QueryClient,
35): CreateBaseQueryResult<TData, TError> {
36 assertInInjectionContext(createBaseQuery)
37 const destroyRef = inject(DestroyRef)
38​
39 /**
40 * Signal that has the default options from query client applied
41 * computed() is used so signals can be inserted into the options
42 * making it reactive. Wrapping options in a function ensures embedded expressions
43 * are preserved and can keep being applied after signal changes
44 */
45 const defaultedOptionsSignal = computed(() => {
46 const defaultedOptions = queryClient.defaultQueryOptions(
47 options(queryClient),
48 )
49 defaultedOptions._optimisticResults = 'optimistic'
50 return defaultedOptions
51 })
52​
53 const observer = new Observer<
54 TQueryFnData,
55 TError,
56 TData,
57 TQueryData,
58 TQueryKey
59 >(queryClient, defaultedOptionsSignal())
60​
61 const resultSignal = signal(
62 observer.getOptimisticResult(defaultedOptionsSignal()),
63 )
64​
65 effect(
66 () => {
67 // Do not notify on updates because of changes in the options because
68 // these changes should already be reflected in the optimistic result.
69 const defaultedOptions = defaultedOptionsSignal()
70 observer.setOptions(defaultedOptions, {
71 listeners: false,
72 })
73 resultSignal.set(observer.getOptimisticResult(defaultedOptions))
74 },
75 { allowSignalWrites: true },
76 )
77​
78 // observer.trackResult is not used as this optimization is not needed for Angular
79 const unsubscribe = observer.subscribe(
80 notifyManager.batchCalls((val) => resultSignal.set(val)),
81 )
82 destroyRef.onDestroy(unsubscribe)
83​
84 return signalProxy(resultSignal) as CreateBaseQueryResult<TData, TError>