Skip to content

Commit 9dbe48c

Browse files
committed
Defer dispatch based on synchronous flag
1 parent 4ddd5d6 commit 9dbe48c

File tree

2 files changed

+26
-22
lines changed

2 files changed

+26
-22
lines changed

packages/react-urql/src/hooks/state.ts

Lines changed: 24 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import * as React from 'react';
1+
import type { Dispatch } from 'react';
22

33
export const initialState = {
44
fetching: false,
@@ -65,27 +65,31 @@ export const hasDepsChanged = <T extends { length: number }>(a: T, b: T) => {
6565
return false;
6666
};
6767

68-
const ReactSharedInternals =
69-
(React as any).__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED ||
70-
(React as any)
71-
.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE;
68+
let isDispatching = false;
7269

73-
export function deferDispatch<Dispatch extends React.Dispatch<any>>(
74-
setState: Dispatch,
75-
value: Dispatch extends React.Dispatch<infer State> ? State : void
76-
) {
77-
if (!!ReactSharedInternals && process.env.NODE_ENV !== 'production') {
78-
const currentOwner = ReactSharedInternals.ReactCurrentOwner
79-
? ReactSharedInternals.ReactCurrentOwner.current
80-
: ReactSharedInternals.A &&
81-
ReactSharedInternals.A.getOwner &&
82-
ReactSharedInternals.A.getOwner();
83-
if (currentOwner) {
84-
Promise.resolve(value).then(setState);
85-
} else {
86-
setState(value);
70+
function deferDispatch<F extends Dispatch<any>>(
71+
setState: F,
72+
value: F extends Dispatch<infer State> ? State : void
73+
): void;
74+
75+
function deferDispatch<F extends Dispatch<any>>(
76+
setState: F
77+
): ReturnType<F>;
78+
79+
function deferDispatch<F extends Dispatch<any>>(
80+
setState: F,
81+
value?: F extends Dispatch<infer State> ? State : void
82+
): any {
83+
if (!isDispatching || value === undefined) {
84+
try {
85+
isDispatching = true;
86+
return setState(value);
87+
} finally {
88+
isDispatching = false;
8789
}
8890
} else {
89-
setState(value);
91+
Promise.resolve(value).then(setState);
9092
}
9193
}
94+
95+
export { deferDispatch };

packages/react-urql/src/hooks/useQuery.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -308,7 +308,7 @@ export function useQuery<
308308
() =>
309309
[
310310
source,
311-
computeNextState(initialState, getSnapshot(source, suspense)),
311+
computeNextState(initialState, deferDispatch(() => getSnapshot(source, suspense))),
312312
deps,
313313
] as const
314314
);
@@ -319,7 +319,7 @@ export function useQuery<
319319
source,
320320
(currentResult = computeNextState(
321321
state[1],
322-
getSnapshot(source, suspense)
322+
deferDispatch(() => getSnapshot(source, suspense))
323323
)),
324324
deps,
325325
]);

0 commit comments

Comments
 (0)