-
Notifications
You must be signed in to change notification settings - Fork 37
/
index.ts
93 lines (78 loc) · 2.79 KB
/
index.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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
'use client';
import {
type ChannelErrorData,
type ConnectionStatus,
type Options,
type UnsubscribeFn,
subscribeToQuery,
} from 'datocms-listen';
import { useState } from 'react';
import { useDeepCompareEffectNoCheck as useDeepCompareEffect } from 'use-deep-compare-effect';
export type SubscribeToQueryOptions<QueryResult, QueryVariables> = Omit<
Options<QueryResult, QueryVariables>,
'onStatusChange' | 'onUpdate' | 'onChannelError'
>;
export type EnabledQueryListenerOptions<QueryResult, QueryVariables> = {
/** Whether the subscription has to be performed or not */
enabled?: true;
/** The initial data to use while the initial request is being performed */
initialData?: QueryResult;
} & SubscribeToQueryOptions<QueryResult, QueryVariables>;
export type DisabledQueryListenerOptions<QueryResult, QueryVariables> = {
/** Whether the subscription has to be performed or not */
enabled: false;
/** The initial data to use while the initial request is being performed */
initialData?: QueryResult;
} & Partial<SubscribeToQueryOptions<QueryResult, QueryVariables>>;
export type QueryListenerOptions<QueryResult, QueryVariables> =
| EnabledQueryListenerOptions<QueryResult, QueryVariables>
| DisabledQueryListenerOptions<QueryResult, QueryVariables>;
export function useQuerySubscription<
// biome-ignore lint/suspicious/noExplicitAny: <explanation>
QueryResult = any,
// biome-ignore lint/suspicious/noExplicitAny: <explanation>
QueryVariables = Record<string, any>,
>(options: QueryListenerOptions<QueryResult, QueryVariables>) {
const { enabled, initialData, ...other } = options;
const [error, setError] = useState<ChannelErrorData | null>(null);
const [data, setData] = useState<QueryResult | null>(null);
const [status, setStatus] = useState<ConnectionStatus>(
enabled ? 'connecting' : 'closed',
);
const subscribeToQueryOptions = other as EnabledQueryListenerOptions<
QueryResult,
QueryVariables
>;
useDeepCompareEffect(() => {
if (enabled === false) {
setStatus('closed');
return () => {
// we don't have to perform any uninstall
};
}
let unsubscribe: UnsubscribeFn | null;
async function subscribe() {
unsubscribe = await subscribeToQuery<QueryResult, QueryVariables>({
...subscribeToQueryOptions,
onStatusChange: (status) => {
setStatus(status);
},
onUpdate: (updateData) => {
setError(null);
setData(updateData.response.data);
},
onChannelError: (errorData) => {
setData(null);
setError(errorData);
},
});
}
subscribe();
return () => {
if (unsubscribe) {
unsubscribe();
}
};
}, [subscribeToQueryOptions]);
return { error, status, data: data || initialData };
}