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

create-base-query.ts

85 lines2.3 KB

1import {
2 DestroyRef,
3 assertInInjectionContext,
4 computed,
5 effect,
6 inject,
7 signal,
8} from '@angular/core'
9import { signalProxy } from './signal-proxy'
10import type { QueryClient, QueryKey, QueryObserver } from '@tanstack/query-core'
11import type { CreateBaseQueryOptions, CreateBaseQueryResult } from './types'
12​
13/**
14 * Base implementation for `injectQuery` and `injectInfiniteQuery`.
15 * @internal
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(
63 queryClient.defaultQueryOptions(defaultedOptionsSignal()),
64 ),
65 )
66​
67 effect(
68 () => {
69 // Do not notify on updates because of changes in the options because
70 // these changes should already be reflected in the optimistic result.
71 const defaultedOptions = defaultedOptionsSignal()
72 observer.setOptions(defaultedOptions, {
73 listeners: false,
74 })
75 resultSignal.set(observer.getOptimisticResult(defaultedOptions))
76 },
77 { allowSignalWrites: true },
78 )
79​
80 // observer.trackResult is not used as this optimization is not needed for Angular
81 const unsubscribe = observer.subscribe(resultSignal.set)
82 destroyRef.onDestroy(unsubscribe)
83​
84 return signalProxy(resultSignal)