forked from facebook/relay
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathuseLoadMoreFunction.js
More file actions
344 lines (318 loc) · 9.63 KB
/
useLoadMoreFunction.js
File metadata and controls
344 lines (318 loc) · 9.63 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
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow strict-local
* @format
* @oncall relay
*/
'use strict';
import type {
ConcreteRequest,
Direction,
Disposable,
GraphQLResponse,
Observer,
ReaderFragment,
ReaderPaginationMetadata,
Variables,
} from 'relay-runtime';
const useFetchTrackingRef = require('./useFetchTrackingRef');
const useIsMountedRef = require('./useIsMountedRef');
const useIsOperationNodeActive = require('./useIsOperationNodeActive');
const useRelayEnvironment = require('./useRelayEnvironment');
const invariant = require('invariant');
const {useCallback, useEffect, useState} = require('react');
const {
__internal: {fetchQuery},
ConnectionInterface,
createOperationDescriptor,
getPaginationVariables,
getSelector,
getValueAtPath,
} = require('relay-runtime');
const warning = require('warning');
export type LoadMoreFn<TVariables: Variables> = (
count: number,
options?: {
onComplete?: (Error | null) => void,
UNSTABLE_extraVariables?: Partial<TVariables>,
},
) => Disposable;
export type UseLoadMoreFunctionArgs = {
direction: Direction,
fragmentNode: ReaderFragment,
fragmentRef: mixed,
fragmentIdentifier: string,
fragmentData: mixed,
connectionPathInFragmentData: $ReadOnlyArray<string | number>,
identifierField: ?string,
paginationRequest: ConcreteRequest,
paginationMetadata: ReaderPaginationMetadata,
componentDisplayName: string,
observer: Observer<GraphQLResponse>,
onReset: () => void,
};
function useLoadMoreFunction<TVariables: Variables>(
args: UseLoadMoreFunctionArgs,
): [LoadMoreFn<TVariables>, boolean, () => void] {
const {
direction,
fragmentNode,
fragmentRef,
fragmentIdentifier,
fragmentData,
connectionPathInFragmentData,
paginationRequest,
paginationMetadata,
componentDisplayName,
observer,
onReset,
identifierField,
} = args;
const environment = useRelayEnvironment();
const {isFetchingRef, startFetch, disposeFetch, completeFetch} =
useFetchTrackingRef();
const identifierValue =
identifierField != null &&
fragmentData != null &&
typeof fragmentData === 'object'
? fragmentData[identifierField]
: null;
const isMountedRef = useIsMountedRef();
const [mirroredEnvironment, setMirroredEnvironment] = useState(environment);
const [mirroredFragmentIdentifier, setMirroredFragmentIdentifier] =
useState(fragmentIdentifier);
const isParentQueryActive = useIsOperationNodeActive(
fragmentNode,
fragmentRef,
);
const shouldReset =
environment !== mirroredEnvironment ||
fragmentIdentifier !== mirroredFragmentIdentifier;
if (shouldReset) {
disposeFetch();
onReset();
setMirroredEnvironment(environment);
setMirroredFragmentIdentifier(fragmentIdentifier);
}
const {cursor, hasMore} = getConnectionState(
direction,
fragmentNode,
fragmentData,
connectionPathInFragmentData,
);
// Dispose of pagination requests in flight when unmounting
useEffect(() => {
return () => {
disposeFetch();
};
}, [disposeFetch]);
const loadMore = useCallback(
(
count: number,
options: void | {
UNSTABLE_extraVariables?: Partial<TVariables>,
onComplete?: (Error | null) => void,
},
) => {
// TODO(T41131846): Fetch/Caching policies for loadMore
const onComplete = options?.onComplete;
if (isMountedRef.current !== true) {
// Bail out and warn if we're trying to paginate after the component
// has unmounted
warning(
false,
'Relay: Unexpected fetch on unmounted component for fragment ' +
'`%s` in `%s`. It looks like some instances of your component are ' +
'still trying to fetch data but they already unmounted. ' +
'Please make sure you clear all timers, intervals, ' +
'async calls, etc that may trigger a fetch.',
fragmentNode.name,
componentDisplayName,
);
return {dispose: () => {}};
}
const fragmentSelector = getSelector(fragmentNode, fragmentRef);
if (
isFetchingRef.current === true ||
fragmentData == null ||
isParentQueryActive
) {
if (fragmentSelector == null) {
warning(
false,
'Relay: Unexpected fetch while using a null fragment ref ' +
'for fragment `%s` in `%s`. When fetching more items, we expect ' +
"initial fragment data to be non-null. Please make sure you're " +
'passing a valid fragment ref to `%s` before paginating.',
fragmentNode.name,
componentDisplayName,
componentDisplayName,
);
}
if (onComplete) {
onComplete(null);
}
return {dispose: () => {}};
}
invariant(
fragmentSelector != null &&
fragmentSelector.kind !== 'PluralReaderSelector',
'Relay: Expected to be able to find a non-plural fragment owner for ' +
"fragment `%s` when using `%s`. If you're seeing this, " +
'this is likely a bug in Relay.',
fragmentNode.name,
componentDisplayName,
);
const parentVariables = fragmentSelector.owner.variables;
const fragmentVariables = fragmentSelector.variables;
const extraVariables = options?.UNSTABLE_extraVariables;
const baseVariables = {
...parentVariables,
...fragmentVariables,
};
const paginationVariables = getPaginationVariables(
direction,
count,
cursor,
baseVariables,
{...extraVariables},
paginationMetadata,
);
// If the query needs an identifier value ('id' or similar) and one
// was not explicitly provided, read it from the fragment data.
if (identifierField != null) {
// @refetchable fragments are guaranteed to have an `id` selection
// if the type is Node, implements Node, or is @fetchable. Double-check
// that there actually is a value at runtime.
if (typeof identifierValue !== 'string') {
warning(
false,
'Relay: Expected result to have a string ' +
'`%s` in order to refetch, got `%s`.',
identifierField,
identifierValue,
);
}
paginationVariables[identifierField] = identifierValue;
}
const paginationQuery = createOperationDescriptor(
paginationRequest,
paginationVariables,
{force: true},
);
fetchQuery(environment, paginationQuery).subscribe({
...observer,
start: subscription => {
startFetch(subscription);
observer.start && observer.start(subscription);
},
complete: () => {
completeFetch();
observer.complete && observer.complete();
onComplete && onComplete(null);
},
error: error => {
completeFetch();
observer.error && observer.error(error);
onComplete && onComplete(error);
},
});
return {dispose: disposeFetch};
},
// NOTE: We disable react-hooks-deps warning because all values
// inside paginationMetadata are static
// eslint-disable-next-line react-hooks/exhaustive-deps
[
environment,
identifierValue,
direction,
cursor,
startFetch,
disposeFetch,
completeFetch,
isFetchingRef,
isParentQueryActive,
fragmentData,
fragmentNode.name,
fragmentRef,
componentDisplayName,
],
);
return [loadMore, hasMore, disposeFetch];
}
function getConnectionState(
direction: Direction,
fragmentNode: ReaderFragment,
fragmentData: mixed,
connectionPathInFragmentData: $ReadOnlyArray<string | number>,
): {
cursor: ?string,
hasMore: boolean,
} {
const {
EDGES,
PAGE_INFO,
HAS_NEXT_PAGE,
HAS_PREV_PAGE,
END_CURSOR,
START_CURSOR,
} = ConnectionInterface.get();
const connection = getValueAtPath(fragmentData, connectionPathInFragmentData);
if (connection == null) {
return {cursor: null, hasMore: false};
}
invariant(
typeof connection === 'object',
'Relay: Expected connection in fragment `%s` to have been `null`, or ' +
'a plain object with %s and %s properties. Instead got `%s`.',
fragmentNode.name,
EDGES,
PAGE_INFO,
connection,
);
const edges = connection[EDGES];
const pageInfo = connection[PAGE_INFO];
if (edges == null || pageInfo == null) {
return {cursor: null, hasMore: false};
}
invariant(
Array.isArray(edges),
'Relay: Expected connection in fragment `%s` to have a plural `%s` field. ' +
'Instead got `%s`.',
fragmentNode.name,
EDGES,
edges,
);
invariant(
typeof pageInfo === 'object',
'Relay: Expected connection in fragment `%s` to have a `%s` field. ' +
'Instead got `%s`.',
fragmentNode.name,
PAGE_INFO,
pageInfo,
);
const cursor =
direction === 'forward'
? pageInfo[END_CURSOR] ?? null
: pageInfo[START_CURSOR] ?? null;
invariant(
cursor === null || typeof cursor === 'string',
'Relay: Expected page info for connection in fragment `%s` to have a ' +
'valid `%s`. Instead got `%s`.',
fragmentNode.name,
START_CURSOR,
cursor,
);
let hasMore;
if (direction === 'forward') {
hasMore = cursor != null && pageInfo[HAS_NEXT_PAGE] === true;
} else {
hasMore = cursor != null && pageInfo[HAS_PREV_PAGE] === true;
}
return {cursor, hasMore};
}
module.exports = useLoadMoreFunction;