-
Notifications
You must be signed in to change notification settings - Fork 2.7k
/
useSubscription.ts
44 lines (38 loc) · 1.49 KB
/
useSubscription.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
import { useContext, useState, useRef, useEffect } from 'react';
import { DocumentNode } from 'graphql';
import { TypedDocumentNode } from '@graphql-typed-document-node/core';
import { SubscriptionHookOptions } from '../types/types';
import { SubscriptionData } from '../data';
import { OperationVariables } from '../../core';
import { getApolloContext } from '../context';
export function useSubscription<TData = any, TVariables = OperationVariables>(
subscription: DocumentNode | TypedDocumentNode<TData, TVariables>,
options?: SubscriptionHookOptions<TData, TVariables>
) {
const context = useContext(getApolloContext());
const updatedOptions = options
? { ...options, subscription }
: { subscription };
const [result, setResult] = useState({
loading: !updatedOptions.skip,
error: undefined,
data: undefined
});
const subscriptionDataRef = useRef<SubscriptionData<TData, TVariables>>();
function getSubscriptionDataRef() {
if (!subscriptionDataRef.current) {
subscriptionDataRef.current = new SubscriptionData<TData, TVariables>({
options: updatedOptions,
context,
setResult
});
}
return subscriptionDataRef.current;
}
const subscriptionData = getSubscriptionDataRef();
subscriptionData.setOptions(updatedOptions, true);
subscriptionData.context = context;
useEffect(() => subscriptionData.afterExecute());
useEffect(() => subscriptionData.cleanup.bind(subscriptionData), []);
return subscriptionData.execute(result);
}