Skip to content

Commit aff5e3e

Browse files
Katarina Antonkaciakmaciak
authored andcommitted
feat(useSubscription): pass queryKey to subscriptionFn
1 parent 7b4c439 commit aff5e3e

File tree

1 file changed

+13
-9
lines changed

1 file changed

+13
-9
lines changed

src/use-subscription.ts

Lines changed: 13 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,10 @@
11
import { useEffect, useRef } from 'react';
2-
import {
2+
import { useQuery, useQueryClient } from 'react-query';
3+
import type {
34
QueryFunction,
45
QueryKey,
5-
useQuery,
6-
useQueryClient,
76
UseQueryResult,
7+
QueryFunctionContext,
88
PlaceholderDataFunction,
99
} from 'react-query';
1010
import type {
@@ -106,7 +106,9 @@ export function useSubscription<
106106
TSubscriptionKey extends QueryKey = QueryKey
107107
>(
108108
subscriptionKey: TSubscriptionKey,
109-
subscriptionFn: () => Observable<TSubscriptionFnData>,
109+
subscriptionFn: (
110+
context: QueryFunctionContext<TSubscriptionKey>
111+
) => Observable<TSubscriptionFnData>,
110112
options: UseSubscriptionOptions<
111113
TSubscriptionFnData,
112114
TError,
@@ -122,16 +124,18 @@ export function useSubscription<
122124
// @todo: move from the component scope to queryCache
123125
const failRefetchWith = useRef<false | Error>(false);
124126

125-
const queryFn: QueryFunction<TSubscriptionFnData, TSubscriptionKey> = ({
126-
queryKey,
127-
}) => {
127+
const queryFn: QueryFunction<TSubscriptionFnData, TSubscriptionKey> = (
128+
context
129+
) => {
130+
const { queryKey } = context;
131+
128132
if (failRefetchWith.current) {
129133
throw failRefetchWith.current;
130134
}
131135

132136
type Result = Promise<TSubscriptionFnData> & { cancel?: () => void };
133137

134-
const stream$ = subscriptionFn().pipe(share());
138+
const stream$ = subscriptionFn(context).pipe(share());
135139
const result: Result = firstValueFrom(stream$);
136140

137141
// Fixes scenario when component unmounts before first emit.
@@ -189,7 +193,7 @@ export function useSubscription<
189193
onError: (error: TError) => {
190194
// Once the error has been thrown, and a query result created (with error)
191195
// cleanup the `failRefetchWith`.
192-
failRefetchWith.current = undefined;
196+
failRefetchWith.current = false;
193197

194198
options.onError && options.onError(error);
195199
},

0 commit comments

Comments
 (0)