From cc60f03f38221b8cbcc64096fad0b95307bca87f 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/renderToCanvas.tsx | 35 ++++++++++++++++++--- 1 file changed, 31 insertions(+), 4 deletions(-) diff --git a/code/renderers/react/src/renderToCanvas.tsx b/code/renderers/react/src/renderToCanvas.tsx index 4ae1acbb7fe9..006d39e8134a 100644 --- a/code/renderers/react/src/renderToCanvas.tsx +++ b/code/renderers/react/src/renderToCanvas.tsx @@ -45,6 +45,23 @@ class ErrorBoundary extends ReactComponent<{ const Wrapper = FRAMEWORK_OPTIONS?.strictMode ? StrictMode : Fragment; +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(); +}; + export async function renderToCanvas( { storyContext, @@ -81,12 +98,22 @@ export async function renderToCanvas( unmountElement(canvasElement); } - await act(async () => { - await renderElement(element, canvasElement, storyContext?.parameters?.react?.rootOptions); + await new Promise((resolve, reject) => { + try { + actQueue.push(async () => { + await act(async () => { + await renderElement(element, canvasElement, storyContext?.parameters?.react?.rootOptions); + resolve(); + }); + }); + processActQueue(); + } catch (e) { + reject(e); + } }); - return async () => { - await act(() => { + return () => { + act(() => { unmountElement(canvasElement); }); };