/
ReactRelayPaginationContainer.js
812 lines (759 loc) · 25 KB
/
ReactRelayPaginationContainer.js
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
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
/**
* Copyright (c) 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactRelayPaginationContainer
* @flow
* @format
*/
'use strict';
const React = require('React');
const RelayProfiler = require('RelayProfiler');
const RelayPropTypes = require('RelayPropTypes');
const areEqual = require('areEqual');
const buildReactRelayContainer = require('buildReactRelayContainer');
const invariant = require('invariant');
const isRelayContext = require('isRelayContext');
const isScalarAndEqual = require('isScalarAndEqual');
const nullthrows = require('nullthrows');
const warning = require('warning');
const {profileContainer} = require('ReactRelayContainerProfiler');
const {getComponentName, getReactComponent} = require('RelayContainerUtils');
const {ConnectionInterface, Observable} = require('RelayRuntime');
import type {
ObserverOrCallback,
GeneratedNodeMap,
RefetchOptions,
RelayPaginationProp,
} from 'ReactRelayTypes';
import type {
CacheConfig,
Disposable,
FragmentSpecResolver,
} from 'RelayCombinedEnvironmentTypes';
import type {ConnectionMetadata} from 'RelayConnectionHandler';
import type {PageInfo} from 'RelayConnectionInterface';
import type {GraphQLTaggedNode} from 'RelayModernGraphQLTag';
import type {Observer, Subscription} from 'RelayObservable';
import type {
FragmentMap,
RelayContext,
RelayResponsePayload,
} from 'RelayStoreTypes';
import type {Variables} from 'RelayTypes';
type ContainerState = {
data: {[key: string]: mixed},
relayProp: RelayPaginationProp,
};
const containerContextTypes = {
relay: RelayPropTypes.Relay,
};
const FORWARD = 'forward';
type FragmentVariablesGetter = (
prevVars: Variables,
totalCount: number,
) => Variables;
export type ConnectionConfig = {
direction?: 'backward' | 'forward',
getConnectionFromProps?: (props: Object) => ?ConnectionData,
getFragmentVariables?: FragmentVariablesGetter,
getVariables: (
props: Object,
paginationInfo: {count: number, cursor: ?string},
fragmentVariables: Variables,
) => Variables,
query: GraphQLTaggedNode,
};
export type ConnectionData = {
edges?: ?Array<any>,
pageInfo?: ?PageInfo,
};
/**
* Extends the functionality of RelayFragmentContainer by providing a mechanism
* to load more data from a connection.
*
* # Configuring a PaginationContainer
*
* PaginationContainer accepts the standard FragmentContainer arguments and an
* additional `connectionConfig` argument:
*
* - `Component`: the component to be wrapped/rendered.
* - `fragments`: an object whose values are `graphql` fragments. The object
* keys determine the prop names by which fragment data is available.
* - `connectionConfig`: an object that determines how to load more connection
* data. Details below.
*
* # Loading More Data
*
* Use `props.relay.hasMore()` to determine if there are more items to load.
*
* ```
* hasMore(): boolean
* ```
*
* Use `props.relay.isLoading()` to determine if a previous call to `loadMore()`
* is still pending. This is convenient for avoiding duplicate load calls.
*
* ```
* isLoading(): boolean
* ```
*
* Use `props.relay.loadMore()` to load more items. This will return null if
* there are no more items to fetch, otherwise it will fetch more items and
* return a Disposable that can be used to cancel the fetch.
*
* `pageSize` should be the number of *additional* items to fetch (not the
* total).
*
* ```
* loadMore(pageSize: number, callback: ?(error: ?Error) => void): ?Disposable
* ```
*
* A complete example:
*
* ```
* class Foo extends React.Component {
* ...
* _onEndReached() {
* if (!this.props.relay.hasMore() || this.props.relay.isLoading()) {
* return;
* }
* this.props.relay.loadMore(10);
* }
* ...
* }
* ```
*
* # Connection Config
*
* Here's an example, followed by details of each config property:
*
* ```
* ReactRelayPaginationContainer.createContainer(
* Component,
* {
* user: graphql`fragment FriendsFragment on User {
* friends(after: $afterCursor first: $count) @connection {
* edges { ... }
* pageInfo {
* startCursor
* endCursor
* hasNextPage
* hasPreviousPage
* }
* }
* }`,
* },
* {
* direction: 'forward',
* getConnectionFromProps(props) {
* return props.user && props.user.friends;
* },
* getFragmentVariables(vars, totalCount) {
* // The component presumably wants *all* edges, not just those after
* // the cursor, so notice that we don't set $afterCursor here.
* return {
* ...vars,
* count: totalCount,
* };
* },
* getVariables(props, {count, cursor}, fragmentVariables) {
* return {
* ...RelayFBCompatQueryConstants.get(),
* id: props.user.id,
* afterCursor: cursor,
* count,
* },
* },
* query: graphql`
* query FriendsQuery($id: ID!, $afterCursor: ID, $count: Int!) {
* node(id: $id) {
* ...FriendsFragment
* }
* }
* `,
* }
* );
* ```
*
* ## Config Properties
*
* - `direction`: Either "forward" to indicate forward pagination using
* after/first, or "backward" to indicate backward pagination using
* before/last.
* - `getConnectionFromProps(props)`: PaginationContainer doesn't magically know
* which connection data you mean to fetch more of (a container might fetch
* multiple connections, but can only paginate one of them). This function is
* given the fragment props only (not full props), and should return the
* connection data. See the above example that returns the friends data via
* `props.user.friends`.
* - `getFragmentVariables(previousVars, totalCount)`: Given the previous variables
* and the new total number of items, get the variables to use when reading
* your fragments. Typically this means setting whatever your local "count"
* variable is to the value of `totalCount`. See the example.
* - `getVariables(props, {count, cursor})`: Get the variables to use when
* fetching the pagination `query`. You may determine the root object id from
* props (see the example that uses `props.user.id`) and may also set whatever
* variables you use for the after/first/before/last calls based on the count
* and cursor.
* - `query`: A query to use when fetching more connection data. This should
* typically reference one of the container's fragment (as in the example)
* to ensure that all the necessary fields for sub-components are fetched.
*/
function createGetConnectionFromProps(metadata: ReactConnectionMetadata) {
const path = metadata.path;
invariant(
path,
'ReactRelayPaginationContainer: Unable to synthesize a ' +
'getConnectionFromProps function.',
);
return props => {
let data = props[metadata.fragmentName];
for (let i = 0; i < path.length; i++) {
if (!data || typeof data !== 'object') {
return null;
}
data = data[path[i]];
}
return data;
};
}
function createGetFragmentVariables(
metadata: ReactConnectionMetadata,
): FragmentVariablesGetter {
const countVariable = metadata.count;
invariant(
countVariable,
'ReactRelayPaginationContainer: Unable to synthesize a ' +
'getFragmentVariables function.',
);
return (prevVars: Variables, totalCount: number) => ({
...prevVars,
[countVariable]: totalCount,
});
}
type ReactConnectionMetadata = ConnectionMetadata & {
fragmentName: string,
};
function findConnectionMetadata(fragments): ReactConnectionMetadata {
let foundConnectionMetadata = null;
let isRelayModern = false;
for (const fragmentName in fragments) {
const fragment = fragments[fragmentName];
const connectionMetadata: ?Array<ConnectionMetadata> = (fragment.metadata &&
fragment.metadata.connection: any);
// HACK: metadata is always set to `undefined` in classic. In modern, even
// if empty, it is set to null (never undefined). We use that knowlege to
// check if we're dealing with classic or modern
if (fragment.metadata !== undefined) {
isRelayModern = true;
}
if (connectionMetadata) {
invariant(
connectionMetadata.length === 1,
'ReactRelayPaginationContainer: Only a single @connection is ' +
'supported, `%s` has %s.',
fragmentName,
connectionMetadata.length,
);
invariant(
!foundConnectionMetadata,
'ReactRelayPaginationContainer: Only a single fragment with ' +
'@connection is supported.',
);
foundConnectionMetadata = {
...connectionMetadata[0],
fragmentName,
};
}
}
if (isRelayModern) {
warning(
foundConnectionMetadata !== null,
'ReactRelayPaginationContainer: A @connection directive must be present.',
);
}
// TODO(t17350438) for modern, this should be an invariant.
return foundConnectionMetadata || ({}: any);
}
function toObserver(observerOrCallback: ?ObserverOrCallback): Observer<void> {
return typeof observerOrCallback === 'function'
? {error: observerOrCallback, complete: observerOrCallback}
: observerOrCallback || {};
}
function createContainerWithFragments<
TConfig,
TClass: React.ComponentType<TConfig>,
>(
Component: TClass,
fragments: FragmentMap,
connectionConfig: ConnectionConfig,
): React.ComponentType<TConfig & {componentRef?: any}> {
const ComponentClass = getReactComponent(Component);
const componentName = getComponentName(Component);
const containerName = `Relay(${componentName})`;
const metadata = findConnectionMetadata(fragments);
const getConnectionFromProps =
connectionConfig.getConnectionFromProps ||
createGetConnectionFromProps(metadata);
const direction = connectionConfig.direction || metadata.direction;
invariant(
direction,
'ReactRelayPaginationContainer: Unable to infer direction of the ' +
'connection, possibly because both first and last are provided.',
);
const getFragmentVariables =
connectionConfig.getFragmentVariables ||
createGetFragmentVariables(metadata);
class Container extends React.Component<$FlowFixMeProps, ContainerState> {
_isARequestInFlight: boolean;
_localVariables: ?Variables;
_refetchSubscription: ?Subscription;
_references: Array<Disposable>;
_relayContext: RelayContext;
_resolver: FragmentSpecResolver;
constructor(props, context) {
super(props, context);
const relay = assertRelayContext(context.relay);
const {createFragmentSpecResolver} = relay.environment.unstable_internal;
this._isARequestInFlight = false;
this._localVariables = null;
this._refetchSubscription = null;
this._references = [];
this._resolver = createFragmentSpecResolver(
relay,
containerName,
fragments,
props,
this._handleFragmentDataUpdate,
);
this._relayContext = {
environment: this.context.relay.environment,
variables: this.context.relay.variables,
};
this.state = {
data: this._resolver.resolve(),
relayProp: this._buildRelayProp(relay),
};
}
/**
* When new props are received, read data for the new props and subscribe
* for updates. Props may be the same in which case previous data and
* subscriptions can be reused.
*/
componentWillReceiveProps(nextProps, nextContext) {
const context = nullthrows(nextContext);
const relay = assertRelayContext(context.relay);
const {
createFragmentSpecResolver,
getDataIDsFromObject,
} = relay.environment.unstable_internal;
const prevIDs = getDataIDsFromObject(fragments, this.props);
const nextIDs = getDataIDsFromObject(fragments, nextProps);
// If the environment has changed or props point to new records then
// previously fetched data and any pending fetches no longer apply:
// - Existing references are on the old environment.
// - Existing references are based on old variables.
// - Pending fetches are for the previous records.
if (
this.context.relay.environment !== relay.environment ||
this.context.relay.variables !== relay.variables ||
!areEqual(prevIDs, nextIDs)
) {
this._release();
this._localVariables = null;
this._relayContext = {
environment: relay.environment,
variables: relay.variables,
};
this._resolver = createFragmentSpecResolver(
relay,
containerName,
fragments,
nextProps,
this._handleFragmentDataUpdate,
);
this.setState({relayProp: this._buildRelayProp(relay)});
} else if (!this._localVariables) {
this._resolver.setProps(nextProps);
}
const data = this._resolver.resolve();
if (data !== this.state.data) {
this.setState({data});
}
}
componentWillUnmount() {
this._release();
}
shouldComponentUpdate(nextProps, nextState, nextContext): boolean {
// Short-circuit if any Relay-related data has changed
if (
nextContext.relay !== this.context.relay ||
nextState.data !== this.state.data ||
nextState.relayProp !== this.state.relayProp
) {
return true;
}
// Otherwise, for convenience short-circuit if all non-Relay props
// are scalar and equal
const keys = Object.keys(nextProps);
for (let ii = 0; ii < keys.length; ii++) {
const key = keys[ii];
if (
!fragments.hasOwnProperty(key) &&
!isScalarAndEqual(nextProps[key], this.props[key])
) {
return true;
}
}
return false;
}
_buildRelayProp(relay: RelayContext): RelayPaginationProp {
return {
hasMore: this._hasMore,
isLoading: this._isLoading,
loadMore: this._loadMore,
refetchConnection: this._refetchConnection,
environment: relay.environment,
};
}
/**
* Render new data for the existing props/context.
*/
_handleFragmentDataUpdate = () => {
const profiler = RelayProfiler.profile(
'ReactRelayPaginationContainer.handleFragmentDataUpdate',
);
this.setState({data: this._resolver.resolve()}, profiler.stop);
};
_getConnectionData(): ?{
cursor: string,
edgeCount: number,
hasMore: boolean,
} {
// Extract connection data and verify there are more edges to fetch
const props = {
...this.props,
...this.state.data,
};
const connectionData = getConnectionFromProps(props);
if (connectionData == null) {
return null;
}
const {
EDGES,
PAGE_INFO,
HAS_NEXT_PAGE,
HAS_PREV_PAGE,
END_CURSOR,
START_CURSOR,
} = ConnectionInterface.get();
invariant(
typeof connectionData === 'object',
'ReactRelayPaginationContainer: Expected `getConnectionFromProps()` in `%s`' +
'to return `null` or a plain object with %s and %s properties, got `%s`.' +
componentName,
EDGES,
PAGE_INFO,
connectionData,
);
const edges = connectionData[EDGES];
const pageInfo = connectionData[PAGE_INFO];
if (edges == null || pageInfo == null) {
return null;
}
invariant(
Array.isArray(edges),
'ReactRelayPaginationContainer: Expected `getConnectionFromProps()` in `%s`' +
'to return an object with %s: Array, got `%s`.',
componentName,
EDGES,
edges,
);
invariant(
typeof pageInfo === 'object',
'ReactRelayPaginationContainer: Expected `getConnectionFromProps()` in `%s`' +
'to return an object with %s: Object, got `%s`.',
componentName,
PAGE_INFO,
pageInfo,
);
const hasMore =
direction === FORWARD
? pageInfo[HAS_NEXT_PAGE]
: pageInfo[HAS_PREV_PAGE];
const cursor =
direction === FORWARD ? pageInfo[END_CURSOR] : pageInfo[START_CURSOR];
if (typeof hasMore !== 'boolean' || typeof cursor !== 'string') {
warning(
false,
'ReactRelayPaginationContainer: Cannot paginate without %s fields in `%s`. ' +
'Be sure to fetch %s (got `%s`) and %s (got `%s`).',
PAGE_INFO,
componentName,
direction === FORWARD ? HAS_NEXT_PAGE : HAS_PREV_PAGE,
hasMore,
direction === FORWARD ? END_CURSOR : START_CURSOR,
cursor,
);
return null;
}
return {
cursor,
edgeCount: edges.length,
hasMore,
};
}
_hasMore = (): boolean => {
const connectionData = this._getConnectionData();
return !!connectionData && connectionData.hasMore;
};
_isLoading = (): boolean => {
return !!this._refetchSubscription;
};
_refetchConnection = (
totalCount: number,
observerOrCallback: ?ObserverOrCallback,
refetchVariables: ?Variables,
): ?Disposable => {
const paginatingVariables = {
count: totalCount,
cursor: null,
totalCount,
};
const fetch = this._fetchPage(
paginatingVariables,
toObserver(observerOrCallback),
{force: true},
refetchVariables,
);
return fetch ? {dispose: fetch.unsubscribe} : null;
};
_loadMore = (
pageSize: number,
observerOrCallback: ?ObserverOrCallback,
options: ?RefetchOptions,
): ?Disposable => {
const connectionData = this._getConnectionData();
if (!connectionData) {
return null;
}
const totalCount = connectionData.edgeCount + pageSize;
if (options && options.force) {
return this._refetchConnection(totalCount, observerOrCallback);
}
const paginatingVariables = {
count: pageSize,
cursor: connectionData.cursor,
totalCount,
};
const fetch = this._fetchPage(
paginatingVariables,
toObserver(observerOrCallback),
options,
);
return fetch ? {dispose: fetch.unsubscribe} : null;
};
_fetchPage(
paginatingVariables: {
count: number,
cursor: ?string,
totalCount: number,
},
observer: Observer<void>,
options: ?RefetchOptions,
refetchVariables: ?Variables,
): ?Subscription {
const {environment} = assertRelayContext(this.context.relay);
const {
createOperationSelector,
getOperation,
getVariablesFromObject,
} = environment.unstable_internal;
const props = {
...this.props,
...this.state.data,
};
let fragmentVariables = getVariablesFromObject(
this._relayContext.variables,
fragments,
this.props,
);
fragmentVariables = {...fragmentVariables, ...refetchVariables};
let fetchVariables = connectionConfig.getVariables(
props,
{
count: paginatingVariables.count,
cursor: paginatingVariables.cursor,
},
// Pass the variables used to fetch the fragments initially
fragmentVariables,
);
invariant(
typeof fetchVariables === 'object' && fetchVariables !== null,
'ReactRelayPaginationContainer: Expected `getVariables()` to ' +
'return an object, got `%s` in `%s`.',
fetchVariables,
componentName,
);
fetchVariables = {
...fetchVariables,
...refetchVariables,
};
this._localVariables = fetchVariables;
const cacheConfig: ?CacheConfig = options
? {force: !!options.force}
: undefined;
if (cacheConfig && options && options.rerunParamExperimental) {
cacheConfig.rerunParamExperimental = options.rerunParamExperimental;
}
const query = getOperation(connectionConfig.query);
const operation = createOperationSelector(query, fetchVariables);
let refetchSubscription = null;
// Immediately retain the results of the query to prevent cached
// data from being evicted
const reference = environment.retain(operation.root);
this._references.push(reference);
if (this._refetchSubscription) {
this._refetchSubscription.unsubscribe();
}
const onNext = (payload, complete) => {
this._relayContext = {
environment: this.context.relay.environment,
variables: {
...this.context.relay.variables,
...fragmentVariables,
},
};
const prevData = this._resolver.resolve();
this._resolver.setVariables(
getFragmentVariables(
fragmentVariables,
paginatingVariables.totalCount,
),
);
const nextData = this._resolver.resolve();
// Workaround slightly different handling for connection in different
// core implementations:
// - Classic core requires the count to be explicitly incremented
// - Modern core automatically appends new items, updating the count
// isn't required to see new data.
//
// `setState` is only required if changing the variables would change the
// resolved data.
// TODO #14894725: remove PaginationContainer equal check
if (!areEqual(prevData, nextData)) {
this.setState({data: nextData}, complete);
} else {
complete();
}
};
const cleanup = () => {
if (this._refetchSubscription === refetchSubscription) {
this._refetchSubscription = null;
this._isARequestInFlight = false;
}
};
this._isARequestInFlight = true;
refetchSubscription = environment
.execute({operation, cacheConfig})
.mergeMap(
payload =>
new Observable(sink => {
onNext(payload, () => {
sink.next(); // pass void to public observer's `next`
sink.complete();
});
}),
)
// use do instead of finally so that observer's `complete` fires after cleanup
.do({
error: cleanup,
complete: cleanup,
unsubscribe: cleanup,
})
.subscribe(observer || {});
this._refetchSubscription = this._isARequestInFlight
? refetchSubscription
: null;
return refetchSubscription;
}
_release() {
this._resolver.dispose();
this._references.forEach(disposable => disposable.dispose());
this._references.length = 0;
if (this._refetchSubscription) {
this._refetchSubscription.unsubscribe();
this._refetchSubscription = null;
this._isARequestInFlight = false;
}
}
getChildContext(): Object {
return {relay: this._relayContext};
}
render() {
if (ComponentClass) {
return (
<ComponentClass
{...this.props}
{...this.state.data}
// TODO: Remove the string ref fallback.
// eslint-disable-next-line react/no-string-refs
ref={this.props.componentRef || 'component'}
relay={this.state.relayProp}
/>
);
} else {
// Stateless functional, doesn't support `ref`
return React.createElement(Component, {
...this.props,
...this.state.data,
relay: this.state.relayProp,
});
}
}
}
profileContainer(Container, 'ReactRelayPaginationContainer');
Container.contextTypes = containerContextTypes;
Container.displayName = containerName;
return (Container: any);
}
function assertRelayContext(relay: mixed): RelayContext {
invariant(
isRelayContext(relay),
'ReactRelayPaginationContainer: Expected `context.relay` to be an object ' +
'conforming to the `RelayContext` interface, got `%s`.',
relay,
);
return (relay: any);
}
/**
* Wrap the basic `createContainer()` function with logic to adapt to the
* `context.relay.environment` in which it is rendered. Specifically, the
* extraction of the environment-specific version of fragments in the
* `fragmentSpec` is memoized once per environment, rather than once per
* instance of the container constructed/rendered.
*/
function createContainer<TBase: React.ComponentType<*>>(
Component: TBase,
fragmentSpec: GraphQLTaggedNode | GeneratedNodeMap,
connectionConfig: ConnectionConfig,
): TBase {
const Container = buildReactRelayContainer(
Component,
fragmentSpec,
(ComponentClass, fragments) =>
createContainerWithFragments(ComponentClass, fragments, connectionConfig),
);
/* $FlowFixMe(>=0.53.0) This comment suppresses an error
* when upgrading Flow's support for React. Common errors found when
* upgrading Flow's React support are documented at
* https://fburl.com/eq7bs81w */
Container.childContextTypes = containerContextTypes;
return Container;
}
module.exports = {createContainer, createContainerWithFragments};