react-relay 20.1.1 → 21.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (154) hide show
  1. package/ReactRelayContext.js +1 -1
  2. package/ReactRelayContext.js.flow +2 -2
  3. package/ReactRelayFragmentContainer.js.flow +8 -9
  4. package/ReactRelayLocalQueryRenderer.js.flow +11 -3
  5. package/ReactRelayLoggingContext.js.flow +3 -3
  6. package/ReactRelayPaginationContainer.js.flow +32 -25
  7. package/ReactRelayQueryFetcher.js.flow +1 -1
  8. package/ReactRelayQueryRenderer.js.flow +2 -2
  9. package/ReactRelayQueryRendererContext.js.flow +2 -2
  10. package/ReactRelayRefetchContainer.js.flow +17 -14
  11. package/ReactRelayTestMocker.js.flow +10 -10
  12. package/ReactRelayTypes.d.ts +377 -0
  13. package/ReactRelayTypes.js.flow +47 -43
  14. package/RelayContext.js.flow +3 -3
  15. package/__flowtests__/ReactRelayFragmentContainer-flowtest.js.flow +11 -11
  16. package/__flowtests__/ReactRelayPaginationContainer-flowtest.js.flow +5 -5
  17. package/__flowtests__/ReactRelayRefetchContainer-flowtest.js.flow +5 -5
  18. package/__flowtests__/RelayModern-flowtest.js.flow +32 -32
  19. package/__flowtests__/RelayModernFlowtest_users.graphql.js.flow +1 -1
  20. package/__flowtests__/__generated__/ReactRelayFragmentContainerFlowtest_viewer.graphql.js.flow +3 -4
  21. package/__flowtests__/__generated__/ReactRelayFragmentContainerFlowtest_viewer2.graphql.js.flow +3 -4
  22. package/__flowtests__/__generated__/ReactRelayPaginationContainerFlowtestQuery.graphql.js.flow +9 -10
  23. package/__flowtests__/__generated__/ReactRelayPaginationContainerFlowtest_viewer.graphql.js.flow +4 -5
  24. package/__flowtests__/__generated__/ReactRelayRefetchContainerFlowtestQuery.graphql.js.flow +9 -10
  25. package/__flowtests__/__generated__/ReactRelayRefetchContainerFlowtest_viewer.graphql.js.flow +4 -5
  26. package/__flowtests__/__generated__/RelayModernFlowtest_badref.graphql.js.flow +3 -4
  27. package/__flowtests__/__generated__/RelayModernFlowtest_notref.graphql.js.flow +3 -4
  28. package/__flowtests__/__generated__/RelayModernFlowtest_user.graphql.js.flow +3 -4
  29. package/__flowtests__/__generated__/RelayModernFlowtest_users.graphql.js.flow +5 -6
  30. package/buildReactRelayContainer.js.flow +5 -5
  31. package/getRootVariablesForFragments.js.flow +1 -1
  32. package/hooks.d.ts +89 -0
  33. package/hooks.js +1 -1
  34. package/hooks.js.flow +23 -8
  35. package/index.d.ts +9 -0
  36. package/index.js +1 -1
  37. package/index.js.flow +40 -14
  38. package/isRelayEnvironment.js.flow +1 -1
  39. package/jest-react/internalAct.js.flow +1 -1
  40. package/legacy.d.ts +143 -0
  41. package/legacy.js +1 -1
  42. package/legacy.js.flow +32 -13
  43. package/lib/ReactRelayFragmentContainer.js +1 -1
  44. package/lib/ReactRelayPaginationContainer.js +8 -8
  45. package/lib/ReactRelayRefetchContainer.js +8 -8
  46. package/lib/ReactRelayTestMocker.js +5 -5
  47. package/lib/hooks.js +18 -8
  48. package/lib/index.js +30 -14
  49. package/lib/legacy.js +26 -13
  50. package/lib/relay-hooks/legacy/useBlockingPaginationFragment.js +5 -5
  51. package/lib/relay-hooks/legacy/useRefetchableFragmentNode.js +34 -34
  52. package/lib/relay-hooks/loadEntryPoint.js +2 -2
  53. package/lib/relay-hooks/loadQuery.js +14 -14
  54. package/lib/relay-hooks/preloadQuery_DEPRECATED.js +10 -10
  55. package/lib/relay-hooks/readFragmentInternal.js +6 -6
  56. package/lib/relay-hooks/rsc/serverFetchQuery.js +20 -0
  57. package/lib/relay-hooks/rsc/serverPreloadQuery.js +31 -0
  58. package/lib/relay-hooks/rsc/serverReadFragment.js +15 -0
  59. package/lib/relay-hooks/rsc/useQueryFromServer.js +62 -0
  60. package/lib/relay-hooks/useFragmentInternal_CURRENT.js +49 -25
  61. package/lib/relay-hooks/useFragmentInternal_EXPERIMENTAL.js +81 -44
  62. package/lib/relay-hooks/useLazyLoadQueryNode.js +32 -19
  63. package/lib/relay-hooks/useMutation.js +6 -14
  64. package/lib/relay-hooks/useMutationAction_EXPERIMENTAL.js +26 -0
  65. package/lib/relay-hooks/usePreloadedQuery.js +52 -47
  66. package/lib/relay-hooks/useQueryLoader.js +2 -2
  67. package/lib/relay-hooks/useQueryLoader_EXPERIMENTAL.js +2 -2
  68. package/lib/relay-hooks/useRefetchableFragmentInternal.js +31 -31
  69. package/lib/rsc-client_EXPERIMENTAL.js +7 -0
  70. package/lib/rsc_EXPERIMENTAL.js +43 -0
  71. package/multi-actor/ActorChange.js.flow +1 -1
  72. package/package.json +3 -2
  73. package/relay-hooks/EntryPointContainer.react.d.ts +22 -0
  74. package/relay-hooks/EntryPointContainer.react.js.flow +6 -6
  75. package/relay-hooks/EntryPointTypes.flow.js.flow +106 -108
  76. package/relay-hooks/LazyLoadEntryPointContainer_DEPRECATED.react.js.flow +23 -21
  77. package/relay-hooks/MatchContainer.d.ts +95 -0
  78. package/relay-hooks/MatchContainer.js.flow +17 -11
  79. package/relay-hooks/NestedRelayEntryPointBuilderUtils.js.flow +3 -9
  80. package/relay-hooks/ProfilerContext.d.ts +18 -0
  81. package/relay-hooks/QueryResource.js.flow +9 -9
  82. package/relay-hooks/RelayEnvironmentProvider.d.ts +16 -0
  83. package/relay-hooks/RelayEnvironmentProvider.js.flow +2 -2
  84. package/relay-hooks/__flowtests__/EntryPointTypes/EntryPointElementConfig-flowtest.js.flow +6 -6
  85. package/relay-hooks/__flowtests__/EntryPointTypes/ExtractQueryTypes-flowtest.js.flow +50 -3
  86. package/relay-hooks/__flowtests__/EntryPointTypes/NestedEntrypoints-flowtest.js.flow +9 -9
  87. package/relay-hooks/__flowtests__/__generated__/useFragmentFlowtest_user.graphql.js.flow +3 -4
  88. package/relay-hooks/__flowtests__/__generated__/useFragmentFlowtest_users.graphql.js.flow +5 -6
  89. package/relay-hooks/__flowtests__/useBlockingPaginationFragment-flowtest.js.flow +27 -32
  90. package/relay-hooks/__flowtests__/useFragment-flowtest.js.flow +25 -25
  91. package/relay-hooks/__flowtests__/usePaginationFragment-flowtest.js.flow +26 -32
  92. package/relay-hooks/__flowtests__/useRefetchableFragment-flowtest.js.flow +23 -30
  93. package/relay-hooks/__flowtests__/utils.js.flow +17 -17
  94. package/relay-hooks/getConnectionState.js.flow +2 -2
  95. package/relay-hooks/legacy/FragmentResource.js.flow +13 -13
  96. package/relay-hooks/legacy/useBlockingPaginationFragment.js.flow +28 -25
  97. package/relay-hooks/legacy/useFragmentNode.js.flow +4 -4
  98. package/relay-hooks/legacy/useRefetchableFragmentNode.js.flow +79 -81
  99. package/relay-hooks/loadEntryPoint.d.ts +14 -0
  100. package/relay-hooks/loadEntryPoint.js.flow +15 -13
  101. package/relay-hooks/loadQuery.d.ts +20 -0
  102. package/relay-hooks/loadQuery.js.flow +19 -19
  103. package/relay-hooks/preloadQuery_DEPRECATED.js.flow +16 -13
  104. package/relay-hooks/prepareEntryPoint_DEPRECATED.js.flow +7 -7
  105. package/relay-hooks/readFragmentInternal.js.flow +11 -11
  106. package/relay-hooks/rsc/serverFetchQuery.js.flow +31 -0
  107. package/relay-hooks/rsc/serverPreloadQuery.js.flow +69 -0
  108. package/relay-hooks/rsc/serverReadFragment.js.flow +33 -0
  109. package/relay-hooks/rsc/useQueryFromServer.js.flow +135 -0
  110. package/relay-hooks/useClientQuery.d.ts +16 -0
  111. package/relay-hooks/useClientQuery.js.flow +2 -2
  112. package/relay-hooks/useEntryPointLoader.d.ts +21 -0
  113. package/relay-hooks/useEntryPointLoader.js.flow +11 -11
  114. package/relay-hooks/useFragment.d.ts +36 -0
  115. package/relay-hooks/useFragment.js.flow +8 -8
  116. package/relay-hooks/useFragmentInternal.js.flow +1 -1
  117. package/relay-hooks/useFragmentInternal_CURRENT.js.flow +54 -22
  118. package/relay-hooks/useFragmentInternal_EXPERIMENTAL.js.flow +95 -46
  119. package/relay-hooks/useIsOperationNodeActive.js.flow +1 -1
  120. package/relay-hooks/useIsParentQueryActive.js.flow +5 -1
  121. package/relay-hooks/useLazyLoadQuery.d.ts +19 -0
  122. package/relay-hooks/useLazyLoadQuery.js.flow +14 -7
  123. package/relay-hooks/useLazyLoadQueryNode.js.flow +67 -28
  124. package/relay-hooks/useLoadMoreFunction.d.ts +56 -0
  125. package/relay-hooks/useLoadMoreFunction.js.flow +7 -6
  126. package/relay-hooks/useLoadMoreFunction_EXPERIMENTAL.js.flow +5 -5
  127. package/relay-hooks/useMemoVariables.js.flow +1 -1
  128. package/relay-hooks/useMutation.d.ts +36 -0
  129. package/relay-hooks/useMutation.js.flow +9 -17
  130. package/relay-hooks/useMutationAction_EXPERIMENTAL.js.flow +68 -0
  131. package/relay-hooks/usePaginationFragment.d.ts +33 -0
  132. package/relay-hooks/usePaginationFragment.js.flow +19 -11
  133. package/relay-hooks/usePrefetchableForwardPaginationFragment.js.flow +23 -18
  134. package/relay-hooks/usePrefetchableForwardPaginationFragment_EXPERIMENTAL.js.flow +23 -18
  135. package/relay-hooks/usePreloadedQuery.d.ts +17 -0
  136. package/relay-hooks/usePreloadedQuery.js.flow +119 -85
  137. package/relay-hooks/useQueryLoader.d.ts +33 -0
  138. package/relay-hooks/useQueryLoader.js.flow +28 -24
  139. package/relay-hooks/useQueryLoader_EXPERIMENTAL.js.flow +10 -10
  140. package/relay-hooks/useRefetchableFragment.d.ts +23 -0
  141. package/relay-hooks/useRefetchableFragment.js.flow +20 -11
  142. package/relay-hooks/useRefetchableFragmentInternal.js.flow +77 -79
  143. package/relay-hooks/useRelayEnvironment.d.ts +10 -0
  144. package/relay-hooks/useRelayLoggingContext.js.flow +1 -1
  145. package/relay-hooks/useSubscribeToInvalidationState.d.ts +19 -0
  146. package/relay-hooks/useSubscribeToInvalidationState.js.flow +1 -1
  147. package/relay-hooks/useSubscription.d.ts +14 -0
  148. package/relay-hooks/useSubscription.js.flow +1 -1
  149. package/rsc-client_EXPERIMENTAL.d.ts +17 -0
  150. package/rsc-client_EXPERIMENTAL.js +10 -0
  151. package/rsc-client_EXPERIMENTAL.js.flow +23 -0
  152. package/rsc_EXPERIMENTAL.d.ts +48 -0
  153. package/rsc_EXPERIMENTAL.js +10 -0
  154. package/rsc_EXPERIMENTAL.js.flow +90 -0
@@ -11,6 +11,7 @@
11
11
 
12
12
  'use strict';
13
13
 
14
+ import type {LazyLoadQueryNodeParamsWithQuery} from './useLazyLoadQueryNode';
14
15
  import type {
15
16
  CacheConfig,
16
17
  FetchPolicy,
@@ -29,7 +30,10 @@ const {
29
30
  // This separate type export is only needed as long as we are injecting
30
31
  // a separate hooks implementation in ./HooksImplementation -- it can
31
32
  // be removed after we stop doing that.
32
- export type UseLazyLoadQueryHookType = hook <TVariables: Variables, TData>(
33
+ export type UseLazyLoadQueryHookType = hook <
34
+ TVariables extends Variables,
35
+ TData,
36
+ >(
33
37
  gqlQuery: Query<TVariables, TData>,
34
38
  variables: TVariables,
35
39
  options?: Options,
@@ -43,19 +47,19 @@ type Options = {
43
47
  * * "network-only": *will* *not* reuse locally cached data, and will *always* send a network request to fetch the query, ignoring any data that might be locally cached in Relay.
44
48
  * * "store-only": *will* *only* reuse locally cached data, and will *never* send a network request to fetch the query. In this case, the responsibility of fetching the query falls to the caller, but this policy could also be used to read and operate on data that is entirely [local](../../guided-tour/updating-data/local-data-updates).
45
49
  */
46
- +fetchPolicy?: FetchPolicy,
50
+ readonly fetchPolicy?: FetchPolicy,
47
51
  /**
48
52
  * A `fetchKey` can be passed to force a re-evaluation of the current query and variables when the component re-renders, even if the variables didn't change, or even if the component isn't remounted (similarly to how passing a different `key` to a React component will cause it to remount). If the `fetchKey` is different from the one used in the previous render, the current query will be re-evaluated against the store, and it might be refetched depending on the current `fetchPolicy` and the state of the cache.
49
53
  */
50
- +fetchKey?: string | number,
54
+ readonly fetchKey?: string | number,
51
55
  /**
52
56
  * Default value: `{force: true}`. Object containing cache config options for the *network layer*. Note that the network layer may contain an *additional* query response cache which will reuse network responses for identical queries. If you want to bypass this cache completely (which is the default behavior), pass `{force: true}` as the value for this option.
53
57
  */
54
- +networkCacheConfig?: CacheConfig,
58
+ readonly networkCacheConfig?: CacheConfig,
55
59
  /**
56
60
  * Undocumented option.
57
61
  */
58
- +UNSTABLE_renderPolicy?: RenderPolicy,
62
+ readonly UNSTABLE_renderPolicy?: RenderPolicy,
59
63
  };
60
64
 
61
65
  /**
@@ -85,7 +89,7 @@ type Options = {
85
89
  * @returns - `data`: Object that contains data which has been read out from the Relay store; the object matches the shape of specified query.
86
90
  * - The Flow type for data will also match this shape, and contain types derived from the GraphQL Schema. For example, the type of `data` above is: `{| user: ?{| name: ?string |} |}`.
87
91
  */
88
- hook useLazyLoadQuery<TVariables: Variables, TData>(
92
+ hook useLazyLoadQuery<TVariables extends Variables, TData>(
89
93
  /**
90
94
  * GraphQL query specified using a `graphql` template literal.
91
95
  */
@@ -108,7 +112,10 @@ hook useLazyLoadQuery<TVariables: Variables, TData>(
108
112
  ? options.networkCacheConfig
109
113
  : {force: true},
110
114
  );
111
- const data = useLazyLoadQueryNode<$FlowFixMe>({
115
+ const data = useLazyLoadQueryNode<
116
+ $FlowFixMe,
117
+ LazyLoadQueryNodeParamsWithQuery,
118
+ >({
112
119
  componentDisplayName: 'useLazyLoadQuery()',
113
120
  fetchKey: options?.fetchKey,
114
121
  fetchObservable: fetchQuery(environment, query),
@@ -17,6 +17,7 @@ import type {
17
17
  Observable,
18
18
  OperationDescriptor,
19
19
  OperationType,
20
+ ReaderFragment,
20
21
  RenderPolicy,
21
22
  } from 'relay-runtime';
22
23
 
@@ -32,47 +33,74 @@ const React = require('react');
32
33
 
33
34
  const {useContext, useEffect, useState, useRef} = React;
34
35
 
35
- hook useLazyLoadQueryNode<TQuery: OperationType>({
36
- query,
37
- componentDisplayName,
38
- fetchObservable,
39
- fetchPolicy,
40
- fetchKey,
41
- renderPolicy,
42
- }: {
36
+ export type LazyLoadQueryNodeParamsWithQuery = Readonly<{
43
37
  query: OperationDescriptor,
44
38
  componentDisplayName: string,
45
39
  fetchObservable: Observable<GraphQLResponse>,
46
40
  fetchPolicy?: ?FetchPolicy,
47
41
  fetchKey?: ?string | ?number,
48
42
  renderPolicy?: ?RenderPolicy,
49
- }): TQuery['response'] {
43
+ }>;
44
+
45
+ /**
46
+ * This param will be used when the query key is not provided
47
+ * (e.g. in usePreloadedQuery)
48
+ */
49
+ export type LazyLoadQueryNodeParamsWithoutQuery = Readonly<{
50
+ componentDisplayName: string,
51
+ fragmentNode: ReaderFragment,
52
+ }>;
53
+
54
+ export type LazyLoadQueryNodeParams =
55
+ | LazyLoadQueryNodeParamsWithQuery
56
+ | LazyLoadQueryNodeParamsWithoutQuery;
57
+
58
+ hook useLazyLoadQueryNode<
59
+ TQuery extends OperationType,
60
+ TParams extends LazyLoadQueryNodeParams = LazyLoadQueryNodeParams,
61
+ >(
62
+ params: TParams,
63
+ ): TParams extends LazyLoadQueryNodeParamsWithQuery
64
+ ? TQuery['response']
65
+ : null {
50
66
  const environment = useRelayEnvironment();
51
67
  const profilerContext = useContext(ProfilerContext);
52
68
  const QueryResource = getQueryResourceForEnvironment(environment);
53
69
 
54
70
  const [forceUpdateKey, forceUpdate] = useState(0);
55
71
  const {startFetch, completeFetch} = useFetchTrackingRef();
56
- const cacheBreaker = `${forceUpdateKey}-${fetchKey ?? ''}`;
57
- const cacheIdentifier = getQueryCacheIdentifier(
58
- environment,
59
- query,
60
- fetchPolicy,
61
- renderPolicy,
62
- cacheBreaker,
63
- );
64
72
 
65
- const preparedQueryResult = profilerContext.wrapPrepareQueryResource(() => {
66
- return QueryResource.prepareWithIdentifier(
67
- cacheIdentifier,
73
+ let cacheIdentifier = null;
74
+ let preparedQueryResult = null;
75
+ let fragmentNode;
76
+ if (params.query != null) {
77
+ const {query, fetchObservable, fetchPolicy, fetchKey, renderPolicy} =
78
+ params;
79
+ const cacheBreaker = `${forceUpdateKey}-${fetchKey ?? ''}`;
80
+ const queryCacheIdentifier = getQueryCacheIdentifier(
81
+ environment,
68
82
  query,
69
- fetchObservable,
70
83
  fetchPolicy,
71
84
  renderPolicy,
72
- {start: startFetch, complete: completeFetch, error: completeFetch},
73
- profilerContext,
85
+ cacheBreaker,
74
86
  );
75
- });
87
+ cacheIdentifier = queryCacheIdentifier;
88
+
89
+ preparedQueryResult = profilerContext.wrapPrepareQueryResource(() => {
90
+ return QueryResource.prepareWithIdentifier(
91
+ queryCacheIdentifier,
92
+ query,
93
+ fetchObservable,
94
+ fetchPolicy,
95
+ renderPolicy,
96
+ {start: startFetch, complete: completeFetch, error: completeFetch},
97
+ profilerContext,
98
+ );
99
+ });
100
+ fragmentNode = preparedQueryResult.fragmentNode;
101
+ } else {
102
+ fragmentNode = params.fragmentNode;
103
+ }
76
104
 
77
105
  const maybeHiddenOrFastRefresh = useRef(false);
78
106
  useEffect(() => {
@@ -103,6 +131,10 @@ hook useLazyLoadQueryNode<TQuery: OperationType>({
103
131
  return;
104
132
  }
105
133
 
134
+ if (preparedQueryResult == null) {
135
+ return;
136
+ }
137
+
106
138
  const disposable = QueryResource.retain(
107
139
  preparedQueryResult,
108
140
  profilerContext,
@@ -117,6 +149,10 @@ hook useLazyLoadQueryNode<TQuery: OperationType>({
117
149
  }, [environment, cacheIdentifier]);
118
150
 
119
151
  useEffect(() => {
152
+ if (preparedQueryResult == null) {
153
+ return;
154
+ }
155
+
120
156
  // Release any temporary retain that's not released. At this point, if the
121
157
  // cacheIdentifier doesn't change, the query is still permanently retained,
122
158
  // and the temporary retain is redundant.
@@ -124,13 +160,16 @@ hook useLazyLoadQueryNode<TQuery: OperationType>({
124
160
  // This effect is intended to run on every commit, thus no dependency
125
161
  });
126
162
 
127
- const {fragmentNode, fragmentRef} = preparedQueryResult;
128
163
  const data = useFragmentInternal(
129
164
  fragmentNode,
130
- fragmentRef,
131
- componentDisplayName,
165
+ preparedQueryResult?.fragmentRef,
166
+ params.componentDisplayName,
132
167
  );
133
- return data;
168
+
169
+ // Flow is confused in understanding the conditional type.
170
+ // We know data is the query response if input params is LazyLoadQueryNodeParamsWithQuery,
171
+ // and void if otherwise.
172
+ return data as $FlowFixMe;
134
173
  }
135
174
 
136
175
  module.exports = useLazyLoadQueryNode;
@@ -0,0 +1,56 @@
1
+ /**
2
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
3
+ *
4
+ * This source code is licensed under the MIT license found in the
5
+ * LICENSE file in the root directory of this source tree.
6
+ */
7
+
8
+ import {
9
+ ConcreteRequest,
10
+ Disposable,
11
+ DisposeFn,
12
+ GraphQLResponse,
13
+ Observer,
14
+ OperationType,
15
+ ReaderFragment,
16
+ ReaderPaginationMetadata,
17
+ VariablesOf,
18
+ } from 'relay-runtime';
19
+
20
+ export type Direction = 'forward' | 'backward';
21
+
22
+ export type LoadMoreFn<TQuery extends OperationType> = (
23
+ count: number,
24
+ options?: {
25
+ onComplete?: ((arg: Error | null) => void) | undefined;
26
+ UNSTABLE_extraVariables?: Partial<VariablesOf<TQuery>> | undefined;
27
+ },
28
+ ) => Disposable;
29
+
30
+ export interface UseLoadMoreFunctionArgs {
31
+ direction: Direction;
32
+ fragmentNode: ReaderFragment;
33
+ fragmentRef: unknown;
34
+ fragmentIdentifier: string;
35
+ fragmentData: unknown;
36
+ connectionPathInFragmentData: ReadonlyArray<string | number>;
37
+ identifierField?: string | null | undefined;
38
+ paginationRequest: ConcreteRequest;
39
+ paginationMetadata: ReaderPaginationMetadata;
40
+ componentDisplayName: string;
41
+ observer: Observer<GraphQLResponse>;
42
+ onReset: () => void;
43
+ }
44
+ export function useLoadMoreFunction<TQuery extends OperationType>(
45
+ args: UseLoadMoreFunctionArgs,
46
+ ): [LoadMoreFn<TQuery>, boolean, DisposeFn];
47
+
48
+ export function getConnectionState(
49
+ direction: Direction,
50
+ fragmentNode: ReaderFragment,
51
+ fragmentData: unknown,
52
+ connectionPathInFragmentData: ReadonlyArray<string | number>,
53
+ ): {
54
+ cursor?: string | null | undefined;
55
+ hasMore: boolean;
56
+ };
@@ -40,7 +40,7 @@ const {
40
40
  } = require('relay-runtime');
41
41
  const warning = require('warning');
42
42
 
43
- export type LoadMoreFn<TVariables: Variables> = (
43
+ export type LoadMoreFn<TVariables extends Variables> = (
44
44
  count: number,
45
45
  options?: {
46
46
  onComplete?: (Error | null) => void,
@@ -51,10 +51,10 @@ export type LoadMoreFn<TVariables: Variables> = (
51
51
  export type UseLoadMoreFunctionArgs = {
52
52
  direction: Direction,
53
53
  fragmentNode: ReaderFragment,
54
- fragmentRef: mixed,
54
+ fragmentRef: unknown,
55
55
  fragmentIdentifier: string,
56
- fragmentData: mixed,
57
- connectionPathInFragmentData: $ReadOnlyArray<string | number>,
56
+ fragmentData: unknown,
57
+ connectionPathInFragmentData: ReadonlyArray<string | number>,
58
58
  paginationRequest: ConcreteRequest,
59
59
  paginationMetadata: ReaderPaginationMetadata,
60
60
  componentDisplayName: string,
@@ -62,12 +62,13 @@ export type UseLoadMoreFunctionArgs = {
62
62
  onReset: () => void,
63
63
  };
64
64
 
65
- hook useLoadMoreFunction<TVariables: Variables>(
65
+ hook useLoadMoreFunction<TVariables extends Variables>(
66
66
  args: UseLoadMoreFunctionArgs,
67
67
  ): [LoadMoreFn<TVariables>, boolean, () => void] {
68
68
  if (RelayFeatureFlags.ENABLE_ACTIVITY_COMPATIBILITY) {
69
69
  // $FlowFixMe[react-rule-hook] - the condition is static
70
70
  // $FlowFixMe[react-rule-hook-conditional]
71
+ // $FlowFixMe[incompatible-type]
71
72
  return useLoadMoreFunction_EXPERIMENTAL(args);
72
73
  }
73
74
  // $FlowFixMe[react-rule-hook] - the condition is static
@@ -75,7 +76,7 @@ hook useLoadMoreFunction<TVariables: Variables>(
75
76
  return useLoadMoreFunction_CURRENT(args);
76
77
  }
77
78
 
78
- hook useLoadMoreFunction_CURRENT<TVariables: Variables>(
79
+ hook useLoadMoreFunction_CURRENT<TVariables extends Variables>(
79
80
  args: UseLoadMoreFunctionArgs,
80
81
  ): [LoadMoreFn<TVariables>, boolean, () => void] {
81
82
  const {
@@ -38,7 +38,7 @@ const {
38
38
  } = require('relay-runtime');
39
39
  const warning = require('warning');
40
40
 
41
- export type LoadMoreFn<TVariables: Variables> = (
41
+ export type LoadMoreFn<TVariables extends Variables> = (
42
42
  count: number,
43
43
  options?: {
44
44
  onComplete?: (Error | null) => void,
@@ -49,10 +49,10 @@ export type LoadMoreFn<TVariables: Variables> = (
49
49
  export type UseLoadMoreFunctionArgs = {
50
50
  direction: Direction,
51
51
  fragmentNode: ReaderFragment,
52
- fragmentRef: mixed,
52
+ fragmentRef: unknown,
53
53
  fragmentIdentifier: string,
54
- fragmentData: mixed,
55
- connectionPathInFragmentData: $ReadOnlyArray<string | number>,
54
+ fragmentData: unknown,
55
+ connectionPathInFragmentData: ReadonlyArray<string | number>,
56
56
  paginationRequest: ConcreteRequest,
57
57
  paginationMetadata: ReaderPaginationMetadata,
58
58
  componentDisplayName: string,
@@ -60,7 +60,7 @@ export type UseLoadMoreFunctionArgs = {
60
60
  onReset: () => void,
61
61
  };
62
62
 
63
- hook useLoadMoreFunction_EXPERIMENTAL<TVariables: Variables>(
63
+ hook useLoadMoreFunction_EXPERIMENTAL<TVariables extends Variables>(
64
64
  args: UseLoadMoreFunctionArgs,
65
65
  ): [
66
66
  // Function to load more data
@@ -21,7 +21,7 @@ const {useState} = require('react');
21
21
  * This is useful when a `variables` object is used as a value in a depencency
22
22
  * array as it might often be constructed during render.
23
23
  */
24
- hook useMemoVariables<TVariables: Variables | null>(
24
+ hook useMemoVariables<TVariables extends Variables | null>(
25
25
  variables: TVariables,
26
26
  ): TVariables {
27
27
  const [mirroredVariables, setMirroredVariables] = useState(variables);
@@ -0,0 +1,36 @@
1
+ /**
2
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
3
+ *
4
+ * This source code is licensed under the MIT license found in the
5
+ * LICENSE file in the root directory of this source tree.
6
+ */
7
+
8
+ import {
9
+ DeclarativeMutationConfig,
10
+ Disposable,
11
+ GraphQLTaggedNode,
12
+ IEnvironment,
13
+ MutationConfig,
14
+ MutationParameters,
15
+ PayloadError,
16
+ SelectorStoreUpdater,
17
+ UploadableMap,
18
+ VariablesOf,
19
+ } from 'relay-runtime';
20
+
21
+ export interface UseMutationConfig<TMutation extends MutationParameters> {
22
+ variables: VariablesOf<TMutation>;
23
+ updater?: SelectorStoreUpdater<TMutation['response']> | null | undefined;
24
+ uploadables?: UploadableMap | undefined;
25
+ optimisticUpdater?: SelectorStoreUpdater<TMutation['response']> | null | undefined;
26
+ optimisticResponse?: TMutation['rawResponse'] | undefined;
27
+ configs?: DeclarativeMutationConfig[] | undefined;
28
+ onError?: ((error: Error) => void | null) | undefined;
29
+ onCompleted?: ((response: TMutation['response'], errors: PayloadError[] | null) => void | null) | undefined;
30
+ onUnsubscribe?: (() => void | null) | undefined;
31
+ }
32
+
33
+ export function useMutation<TMutation extends MutationParameters>(
34
+ mutation: GraphQLTaggedNode,
35
+ commitMutationFn?: (environment: IEnvironment, config: MutationConfig<TMutation>) => Disposable,
36
+ ): [(config: UseMutationConfig<TMutation>) => Disposable, boolean];
@@ -24,14 +24,13 @@ import type {
24
24
  Variables,
25
25
  } from 'relay-runtime';
26
26
 
27
- const useIsMountedRef = require('./useIsMountedRef');
28
27
  const useRelayEnvironment = require('./useRelayEnvironment');
29
28
  const React = require('react');
30
29
  const {commitMutation: defaultCommitMutation} = require('relay-runtime');
31
30
 
32
31
  const {useState, useEffect, useRef, useCallback} = React;
33
32
 
34
- export type UseMutationConfig<TMutation: MutationParameters> = {
33
+ export type UseMutationConfig<TMutation extends MutationParameters> = {
35
34
  configs?: Array<DeclarativeMutationConfig>,
36
35
  onError?: ?(error: Error) => void,
37
36
  onCompleted?: ?(
@@ -41,7 +40,7 @@ export type UseMutationConfig<TMutation: MutationParameters> = {
41
40
  onNext?: ?() => void,
42
41
  onUnsubscribe?: ?() => void,
43
42
  optimisticResponse?: {
44
- +rawResponse?: {...},
43
+ readonly rawResponse?: {...},
45
44
  ...TMutation,
46
45
  ...
47
46
  }['rawResponse'],
@@ -64,7 +63,7 @@ type UseMutationConfigInternal<TVariables, TData, TRawResponse> = {
64
63
  variables: TVariables,
65
64
  };
66
65
 
67
- hook useMutation<TVariables: Variables, TData, TRawResponse = {...}>(
66
+ hook useMutation<TVariables extends Variables, TData, TRawResponse = {...}>(
68
67
  mutation: Mutation<TVariables, TData, TRawResponse>,
69
68
  commitMutationFn?: (
70
69
  environment: IEnvironment,
@@ -75,7 +74,6 @@ hook useMutation<TVariables: Variables, TData, TRawResponse = {...}>(
75
74
  boolean,
76
75
  ] {
77
76
  const environment = useRelayEnvironment();
78
- const isMountedRef = useIsMountedRef();
79
77
  const environmentRef = useRef(environment);
80
78
  const mutationRef = useRef(mutation);
81
79
  const inFlightMutationsRef = useRef(new Set<Disposable>());
@@ -88,12 +86,10 @@ hook useMutation<TVariables: Variables, TData, TRawResponse = {...}>(
88
86
  mutationRef.current === mutation
89
87
  ) {
90
88
  inFlightMutationsRef.current.delete(disposable);
91
- if (isMountedRef.current) {
92
- setMutationInFlight(inFlightMutationsRef.current.size > 0);
93
- }
89
+ setMutationInFlight(inFlightMutationsRef.current.size > 0);
94
90
  }
95
91
  },
96
- [environment, isMountedRef, mutation],
92
+ [environment, mutation],
97
93
  );
98
94
 
99
95
  useEffect(() => {
@@ -102,19 +98,15 @@ hook useMutation<TVariables: Variables, TData, TRawResponse = {...}>(
102
98
  mutationRef.current !== mutation
103
99
  ) {
104
100
  inFlightMutationsRef.current = new Set();
105
- if (isMountedRef.current) {
106
- setMutationInFlight(false);
107
- }
101
+ setMutationInFlight(false);
108
102
  environmentRef.current = environment;
109
103
  mutationRef.current = mutation;
110
104
  }
111
- }, [environment, isMountedRef, mutation]);
105
+ }, [environment, mutation]);
112
106
 
113
107
  const commit = useCallback(
114
108
  (config: UseMutationConfigInternal<TVariables, TData, TRawResponse>) => {
115
- if (isMountedRef.current) {
116
- setMutationInFlight(true);
117
- }
109
+ setMutationInFlight(true);
118
110
  const disposable: Disposable = commitMutationFn(environment, {
119
111
  ...config,
120
112
  mutation,
@@ -137,7 +129,7 @@ hook useMutation<TVariables: Variables, TData, TRawResponse = {...}>(
137
129
  inFlightMutationsRef.current.add(disposable);
138
130
  return disposable;
139
131
  },
140
- [cleanup, commitMutationFn, environment, isMountedRef, mutation],
132
+ [cleanup, commitMutationFn, environment, mutation],
141
133
  );
142
134
 
143
135
  return [commit, isMutationInFlight];
@@ -0,0 +1,68 @@
1
+ /**
2
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
3
+ *
4
+ * This source code is licensed under the MIT license found in the
5
+ * LICENSE file in the root directory of this source tree.
6
+ *
7
+ * @flow strict-local
8
+ * @format
9
+ * @oncall relay
10
+ */
11
+
12
+ 'use strict';
13
+
14
+ import type {Mutation, Variables} from 'relay-runtime';
15
+
16
+ const useRelayEnvironment = require('./useRelayEnvironment');
17
+ const React = require('react');
18
+ const {commitMutation} = require('relay-runtime');
19
+
20
+ const {useCallback} = React;
21
+
22
+ /**
23
+ * A variant of useMutation that returns an action function suitable for use
24
+ * with React's action prop pattern. The returned action is an async function
25
+ * that can be passed to `startTransition` or used as an action prop, enabling
26
+ * optimistic UI updates via `useOptimistic`.
27
+ * https://react.dev/reference/react/useTransition#starttransition
28
+ *
29
+ * Usage:
30
+ * const commitAction = useMutationAction_EXPERIMENTAL(mutation);
31
+ *
32
+ * // In a startTransition or action prop:
33
+ * startTransition(async () => {
34
+ * setOptimisticValue(newValue);
35
+ * await commitAction({input: newValue});
36
+ * });
37
+ */
38
+ hook useMutationAction_EXPERIMENTAL<
39
+ TVariables extends Variables,
40
+ TData,
41
+ TRawResponse = {...},
42
+ >(
43
+ mutation: Mutation<TVariables, TData, TRawResponse>,
44
+ ): (variables: TVariables) => Promise<TData> {
45
+ const environment = useRelayEnvironment();
46
+
47
+ const commitAction = useCallback(
48
+ (variables: TVariables): Promise<TData> => {
49
+ return new Promise((resolve, reject) => {
50
+ commitMutation(environment, {
51
+ mutation,
52
+ variables,
53
+ onCompleted: (response: TData) => {
54
+ resolve(response);
55
+ },
56
+ onError: (error: Error) => {
57
+ reject(error);
58
+ },
59
+ });
60
+ });
61
+ },
62
+ [environment, mutation],
63
+ );
64
+
65
+ return commitAction;
66
+ }
67
+
68
+ module.exports = useMutationAction_EXPERIMENTAL;
@@ -0,0 +1,33 @@
1
+ /**
2
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
3
+ *
4
+ * This source code is licensed under the MIT license found in the
5
+ * LICENSE file in the root directory of this source tree.
6
+ */
7
+
8
+ import {KeyType, KeyTypeData, RefetchFnDynamic} from '../ReactRelayTypes';
9
+ import { LoadMoreFn } from './useLoadMoreFunction';
10
+ import {GraphQLTaggedNode, OperationType} from 'relay-runtime';
11
+
12
+ export interface usePaginationFragmentHookType<
13
+ TQuery extends OperationType,
14
+ TKey extends KeyType | null | undefined,
15
+ TFragmentData,
16
+ > {
17
+ data: TFragmentData;
18
+ loadNext: LoadMoreFn<TQuery>;
19
+ loadPrevious: LoadMoreFn<TQuery>;
20
+ hasNext: boolean;
21
+ hasPrevious: boolean;
22
+ isLoadingNext: boolean;
23
+ isLoadingPrevious: boolean;
24
+ refetch: RefetchFnDynamic<TQuery, TKey>;
25
+ }
26
+ export function usePaginationFragment<TQuery extends OperationType, TKey extends KeyType>(
27
+ fragmentInput: GraphQLTaggedNode,
28
+ parentFragmentRef: TKey,
29
+ ): usePaginationFragmentHookType<TQuery, TKey, KeyTypeData<TKey>>;
30
+ export function usePaginationFragment<TQuery extends OperationType, TKey extends KeyType>(
31
+ fragmentInput: GraphQLTaggedNode,
32
+ parentFragmentRef: TKey | null | undefined,
33
+ ): usePaginationFragmentHookType<TQuery, TKey | null, KeyTypeData<TKey> | null | undefined>;
@@ -32,11 +32,16 @@ const {
32
32
  getPaginationMetadata,
33
33
  } = require('relay-runtime');
34
34
 
35
- type RefetchVariables<TVariables, TKey: ?{+$fragmentSpreads: mixed, ...}> =
35
+ type RefetchVariables<
36
+ TVariables,
37
+ TKey extends ?{readonly $fragmentSpreads: unknown, ...},
38
+ > =
36
39
  // NOTE: This type ensures that the type of the returned variables is either:
37
40
  // - nullable if the provided ref type is nullable
38
41
  // - non-nullable if the provided ref type is non-nullable
39
- [+key: TKey] extends [+key: {+$fragmentSpreads: mixed, ...}]
42
+ [readonly key: TKey] extends [
43
+ readonly key: {readonly $fragmentSpreads: unknown, ...},
44
+ ]
40
45
  ? Partial<TVariables>
41
46
  : TVariables;
42
47
 
@@ -54,7 +59,9 @@ export type ReturnType<TVariables, TData, TKey> = {
54
59
  // NOTE: This type ensures that the type of the returned data is either:
55
60
  // - nullable if the provided ref type is nullable
56
61
  // - non-nullable if the provided ref type is non-nullable
57
- data: [+key: TKey] extends [+key: {+$fragmentSpreads: mixed, ...}]
62
+ data: [readonly key: TKey] extends [
63
+ readonly key: {readonly $fragmentSpreads: unknown, ...},
64
+ ]
58
65
  ? TData
59
66
  : ?TData,
60
67
  loadNext: LoadMoreFn<TVariables>,
@@ -70,20 +77,20 @@ export type ReturnType<TVariables, TData, TKey> = {
70
77
  // a separate hooks implementation in ./HooksImplementation -- it can
71
78
  // be removed after we stop doing that.
72
79
  export type UsePaginationFragmentType = <
73
- TFragmentType: FragmentType,
74
- TVariables: Variables,
80
+ TFragmentType extends FragmentType,
81
+ TVariables extends Variables,
75
82
  TData,
76
- TKey: ?{+$fragmentSpreads: TFragmentType, ...},
83
+ TKey extends ?{readonly $fragmentSpreads: TFragmentType, ...},
77
84
  >(
78
85
  fragmentInput: RefetchableFragment<TFragmentType, TData, TVariables>,
79
86
  parentFragmentRef: TKey,
80
87
  ) => ReturnType<TVariables, TData, TKey>;
81
88
 
82
89
  hook usePaginationFragment<
83
- TFragmentType: FragmentType,
84
- TVariables: Variables,
90
+ TFragmentType extends FragmentType,
91
+ TVariables extends Variables,
85
92
  TData,
86
- TKey: ?{+$fragmentSpreads: TFragmentType, ...},
93
+ TKey extends ?{readonly $fragmentSpreads: TFragmentType, ...},
87
94
  >(
88
95
  fragmentInput: RefetchableFragment<TFragmentType, TData, TVariables>,
89
96
  parentFragmentRef: TKey,
@@ -155,7 +162,7 @@ hook usePaginationFragment<
155
162
  });
156
163
  }
157
164
  return {
158
- // $FlowFixMe[incompatible-return]
165
+ // $FlowFixMe[incompatible-type]
159
166
  data: fragmentData,
160
167
  loadNext,
161
168
  loadPrevious,
@@ -163,11 +170,12 @@ hook usePaginationFragment<
163
170
  hasPrevious,
164
171
  isLoadingNext,
165
172
  isLoadingPrevious,
173
+ // $FlowFixMe[incompatible-type]
166
174
  refetch: refetchPagination,
167
175
  };
168
176
  }
169
177
 
170
- hook useLoadMore<TVariables: Variables>(
178
+ hook useLoadMore<TVariables extends Variables>(
171
179
  args: Omit<UseLoadMoreFunctionArgs, 'observer' | 'onReset'>,
172
180
  ): [LoadMoreFn<TVariables>, boolean, boolean, () => void] {
173
181
  const environment = useRelayEnvironment();