From 73b1e5191a9e1a248bc01aed4dbccab7de5506d3 Mon Sep 17 00:00:00 2001 From: Mike Hernas Date: Mon, 8 Apr 2024 10:29:49 +0200 Subject: [PATCH] Improvement --- packages/realm-react/src/cachedCollection.ts | 14 +++++--------- 1 file changed, 5 insertions(+), 9 deletions(-) diff --git a/packages/realm-react/src/cachedCollection.ts b/packages/realm-react/src/cachedCollection.ts index 3e9404802e6..7027b8f5bb6 100644 --- a/packages/realm-react/src/cachedCollection.ts +++ b/packages/realm-react/src/cachedCollection.ts @@ -182,13 +182,12 @@ export function createCachedCollection>({ } }; - let wasSetImmediate = false; + let setImmediateId: ReturnType | undefined = undefined; if (!isDerived) { // If we are in a transaction, then push adding the listener to the event loop. This will allow the write transaction to finish. // see https://github.com/realm/realm-js/issues/4375 if (realm.isInTransaction) { - wasSetImmediate = true; - setImmediate(() => { + setImmediateId = setImmediate(() => { collection.addListener(listenerCallback, keyPaths); }); } else { @@ -198,13 +197,10 @@ export function createCachedCollection>({ const tearDown = () => { if (!isDerived) { - if(wasSetImmediate) { - setImmediate(() => { - collection.removeListener(listenerCallback); - }); - } else { - collection.removeListener(listenerCallback); + if (setImmediateId) { + clearImmediate(setImmediateId); } + collection.removeListener(listenerCallback); objectCache.clear(); } };