main
js 63 lines 2.08 KB
Raw
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
8 */
9
10 import {disableLegacyMode} from 'shared/ReactFeatureFlags';
11 import {DiscreteEventPriority} from 'react-reconciler/src/ReactEventPriorities';
12
13 import ReactSharedInternals from 'shared/ReactSharedInternals';
14
15 import ReactDOMSharedInternals from 'shared/ReactDOMSharedInternals';
16
17 declare function flushSyncImpl<R>(fn: () => R): R;
18 declare function flushSyncImpl(void): void;
19 function flushSyncImpl<R>(fn: (() => R) | void): R | void {
20 const previousTransition = ReactSharedInternals.T;
21 const previousUpdatePriority =
22 ReactDOMSharedInternals.p; /* ReactDOMCurrentUpdatePriority */
23
24 try {
25 ReactSharedInternals.T = null;
26 ReactDOMSharedInternals.p /* ReactDOMCurrentUpdatePriority */ =
27 DiscreteEventPriority;
28 if (fn) {
29 return fn();
30 } else {
31 return undefined;
32 }
33 } finally {
34 ReactSharedInternals.T = previousTransition;
35 ReactDOMSharedInternals.p /* ReactDOMCurrentUpdatePriority */ =
36 previousUpdatePriority;
37 const wasInRender =
38 ReactDOMSharedInternals.d /* ReactDOMCurrentDispatcher */
39 .f(); /* flushSyncWork */
40 if (__DEV__) {
41 if (wasInRender) {
42 console.error(
43 'flushSync was called from inside a lifecycle method. React cannot ' +
44 'flush when React is already rendering. Consider moving this call to ' +
45 'a scheduler task or micro task.',
46 );
47 }
48 }
49 }
50 }
51
52 declare function flushSyncErrorInBuildsThatSupportLegacyMode<R>(fn: () => R): R;
53 declare function flushSyncErrorInBuildsThatSupportLegacyMode(void): void;
54 function flushSyncErrorInBuildsThatSupportLegacyMode() {
55 // eslint-disable-next-line react-internal/prod-error-codes
56 throw new Error(
57 'Expected this build of React to not support legacy mode but it does. This is a bug in React.',
58 );
59 }
60
61 export const flushSync: typeof flushSyncImpl = disableLegacyMode
62 ? flushSyncImpl
63 : flushSyncErrorInBuildsThatSupportLegacyMode;