-
-
Notifications
You must be signed in to change notification settings - Fork 35
Expand file tree
/
Copy pathuseRefetch.ts
More file actions
126 lines (112 loc) · 3.54 KB
/
Copy pathuseRefetch.ts
File metadata and controls
126 lines (112 loc) · 3.54 KB
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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
import {
GQtyError,
Selection,
type BaseGeneratedSchema,
type GQtyClient,
type RetryOptions,
} from 'gqty';
import * as React from 'react';
import { type ReactClientOptionsWithDefaults } from '../utils';
interface UseRefetchState {
isLoading: boolean;
error?: GQtyError;
startWatching: () => void;
stopWatching: () => void;
}
export interface UseRefetchOptions {
notifyOnNetworkStatusChange?: boolean;
operationName?: string;
retry?: RetryOptions;
startWatching?: boolean;
suspense?: boolean;
/** Custom GraphQL extensions to be exposed to the query fetcher. */
extensions?: Record<string, unknown>;
}
export interface UseRefetch<TSchema extends BaseGeneratedSchema> {
(
refetchOptions?: UseRefetchOptions
): (<T = void>(
refetchArg?: T | ((query: TSchema['query']) => T)
) => Promise<T | undefined>) &
UseRefetchState;
}
export const createUseRefetch = <TSchema extends BaseGeneratedSchema>(
client: GQtyClient<TSchema>,
{ defaults: { retry: defaultRetry } }: ReactClientOptionsWithDefaults
) => {
const useRefetch: UseRefetch<TSchema> = ({
notifyOnNetworkStatusChange = true,
operationName,
startWatching = true,
retry = defaultRetry,
suspense = false,
extensions,
} = {}) => {
const [state, setState] = React.useState<{
error?: GQtyError;
promise?: Promise<unknown>;
}>();
const watchingRef = React.useRef(startWatching);
const [selections] = React.useState(() => new Set<Selection>());
// All selections from this component down the rendering tree, this almost
// 100% guaranteed to be more than necessary as a refetch. This is necessary
// as long as useRefetch() exists as a separate hook, and accepts no
// parameters as one of the overloads. React provides no way to identify a
// component and potentially gain access to the SchemaContext from other
// query hooks.
const [unsubscribeSelections] = React.useState(() =>
client.subscribeLegacySelections((selection) => {
if (watchingRef.current && selection.root.key === 'query') {
selections.add(selection);
}
})
);
React.useEffect(() => unsubscribeSelections, [unsubscribeSelections]);
if (suspense) {
if (state?.promise) throw state?.promise;
if (state?.error) throw state?.error;
}
const refetch = React.useCallback(
async <T = void>(
fnArg?: T | ((query: TSchema['query']) => T)
): Promise<T | undefined> => {
const promise = (() => {
if (fnArg) return client.refetch(fnArg);
const { context, resolve } = client.createResolver({
retryPolicy: retry,
operationName,
extensions,
});
selections.forEach((selection) => {
context.select(selection);
});
return resolve() as Promise<T>;
})();
setState({ promise });
try {
return (await promise) as T;
} catch (error) {
const theError = GQtyError.create(error);
setState({ error: theError });
throw theError;
}
},
[notifyOnNetworkStatusChange, operationName, retry, extensions]
);
return React.useMemo(
() =>
Object.assign(refetch, {
isLoading: state?.promise !== undefined,
error: state?.error,
startWatching: () => {
watchingRef.current = true;
},
stopWatching: () => {
watchingRef.current = false;
},
}),
[]
);
};
return useRefetch;
};