|
1 | 1 | import { |
| 2 | + computed, |
2 | 3 | EnvironmentInjector, |
3 | 4 | type Injector, |
4 | 5 | inject, |
@@ -60,36 +61,38 @@ export function injectDataConnectQuery<Data, Variables>( |
60 | 61 | Partial<QueryResult<Data, Variables>> | undefined |
61 | 62 | >(undefined); |
62 | 63 | const finalInjector = injector || inject(EnvironmentInjector); |
63 | | - const queryKey = signal<QueryKey>([]); |
64 | | - |
65 | | - function fdcOptionsFn() { |
66 | | - const passedInOptions = |
67 | | - typeof queryRefOrOptionsFn === "function" |
68 | | - ? queryRefOrOptionsFn() |
69 | | - : undefined; |
70 | | - |
71 | | - const modifiedFn = async (): Promise<Data> => { |
72 | | - const ref: QueryRef<Data, Variables> = |
73 | | - passedInOptions?.queryFn() || |
74 | | - (queryRefOrOptionsFn as QueryRef<Data, Variables>); |
75 | | - dataConnectResult.set({ ref }); |
76 | | - // @ts-expect-error function is hidden under `DataConnect`. |
77 | | - ref.dataConnect._setCallerSdkType(_callerSdkType); |
78 | | - queryKey.set([ref.name, ref.variables]); |
79 | | - const response = await executeQuery(ref); |
80 | | - dataConnectResult.set(response); |
81 | | - return response.data; |
82 | | - }; |
| 64 | + const derivedOptions = computed(() => { |
| 65 | + if (typeof queryRefOrOptionsFn === "function") { |
| 66 | + const options = queryRefOrOptionsFn(); |
| 67 | + const queryRef = options.queryFn(); |
| 68 | + return { options, queryRef }; |
| 69 | + } |
83 | 70 | return { |
84 | | - queryKey: queryKey(), |
85 | | - ...passedInOptions, |
86 | | - queryFn: modifiedFn, |
| 71 | + options: undefined, |
| 72 | + queryRef: queryRefOrOptionsFn as QueryRef<Data, Variables>, |
87 | 73 | }; |
88 | | - } |
| 74 | + }); |
| 75 | + const queryRefSignal = computed(() => derivedOptions().queryRef); |
| 76 | + const optionsSignal = computed(() => derivedOptions().options); |
| 77 | + const varsSignal = computed(() => derivedOptions().queryRef.variables); |
89 | 78 |
|
90 | | - const originalResult = injectQuery(fdcOptionsFn, finalInjector); |
| 79 | + async function queryFn() { |
| 80 | + const queryRef = queryRefSignal(); |
| 81 | + // @ts-expect-error function is hidden under `DataConnect`. |
| 82 | + queryRef.dataConnect._setCallerSdkType(_callerSdkType); |
| 83 | + const response = await executeQuery(queryRef); |
| 84 | + dataConnectResult.set(response); |
| 85 | + return response.data; |
| 86 | + } |
| 87 | + const injectQueryResult = injectQuery(() => { |
| 88 | + return { |
| 89 | + queryKey: [queryRefSignal().name, varsSignal()], |
| 90 | + ...optionsSignal(), |
| 91 | + queryFn: queryFn, |
| 92 | + }; |
| 93 | + }, finalInjector); |
91 | 94 | return { |
92 | | - ...originalResult, |
| 95 | + ...injectQueryResult, |
93 | 96 | dataConnectResult, |
94 | 97 | }; |
95 | 98 | } |
|
0 commit comments