From 055c5392b9fc6a2fc373ebf73e9cd6b4398c864a Mon Sep 17 00:00:00 2001 From: Aria Minaei Date: Mon, 5 Jul 2021 00:30:16 +0200 Subject: [PATCH] Fix the infinite loop in dataverse-react --- packages/dataverse-react/src/index.ts | 41 +++++++++++++++++---------- 1 file changed, 26 insertions(+), 15 deletions(-) diff --git a/packages/dataverse-react/src/index.ts b/packages/dataverse-react/src/index.ts index 9479ca5..79eafa2 100644 --- a/packages/dataverse-react/src/index.ts +++ b/packages/dataverse-react/src/index.ts @@ -56,8 +56,8 @@ export function usePrism( return useDerivation(derivation, debugLabel) } -export const useVal: typeof val = (p) => { - return usePrism(() => val(p), [p]) +export const useVal: typeof val = (p, debugLabel?: string) => { + return usePrism(() => val(p), [p], debugLabel) } /** @@ -87,19 +87,7 @@ let microtaskIsQueued = false const pushToQueue = (item: QueueItem) => { _pushToQueue(item) - if (!microtaskIsQueued) { - microtaskIsQueued = true - queueMicrotask(() => { - while (queue.length > 0) { - unstable_batchedUpdates(() => { - for (const item of queue) { - item.runUpdate() - } - }) - } - microtaskIsQueued = false - }) - } + queueIfNeeded() } const _pushToQueue = (item: QueueItem) => { @@ -132,6 +120,28 @@ const removeFromQueue = (item: QueueItem) => { queue.splice(index, 1) } +function queueIfNeeded() { + if (!microtaskIsQueued) { + microtaskIsQueued = true + queueMicrotask(() => { + let i = 0 + while (queue.length > 0) { + i++ + if (i > 5) { + setTimeout(queueIfNeeded, 1) + break + } + unstable_batchedUpdates(() => { + for (const item of queue) { + item.runUpdate() + } + }) + } + microtaskIsQueued = false + }) + } +} + /** * @remarks * It looks like this new implementation of useDerivation() manages to: @@ -151,6 +161,7 @@ function useDerivation(der: IDerivation, debugLabel?: string): T { const refs = useRef<{queueItem: QueueItem; unmounted: boolean}>( undefined as $IntentionalAny, ) + if (!refs.current) { lastOrder++ refs.current = {