From 0f5d5516f5dba79bf01b55edf2d787522acdd1ab Mon Sep 17 00:00:00 2001 From: Valentin Palkovic Date: Mon, 6 Jan 2025 12:16:12 +0100 Subject: [PATCH] React: Force act running always in sequence --- code/renderers/react/src/act-compat.ts | 36 +++++++++++++++++++++++++- 1 file changed, 35 insertions(+), 1 deletion(-) diff --git a/code/renderers/react/src/act-compat.ts b/code/renderers/react/src/act-compat.ts index 7d64e0f7c3be..59a51fe9e0a0 100644 --- a/code/renderers/react/src/act-compat.ts +++ b/code/renderers/react/src/act-compat.ts @@ -68,7 +68,41 @@ function withGlobalActEnvironment(actImplementation: (callback: () => void) => P }; } +const actQueue: (() => Promise)[] = []; +let isActing = false; + +const processActQueue = async () => { + if (isActing || actQueue.length === 0) { + return; + } + + isActing = true; + const actTask = actQueue.shift(); + if (actTask) { + await actTask(); + } + isActing = false; + processActQueue(); +}; + +function withQueuedActEnvironment(actImplementation: (callback: () => void) => Promise) { + const wrappedAct = withGlobalActEnvironment(actImplementation); + return (callback: () => any) => { + return new Promise((resolve, reject) => { + actQueue.push(async () => { + try { + await wrappedAct(callback); + resolve(); + } catch (error) { + reject(error); + } + }); + processActQueue(); + }); + }; +} + export const act = process.env.NODE_ENV === 'production' ? (cb: (...args: any[]) => any) => cb() - : withGlobalActEnvironment(reactAct); + : withQueuedActEnvironment(reactAct);