Skip to content

Commit

Permalink
fix(ui): properly instantiates abort controllers (#10309)
Browse files Browse the repository at this point in the history
Fixes #10296. When an async `useEffect` runs twice or more before
resolving, we use the Abort Controller API to cancel previous events.
This works by instantiating a new ref on each run, and if a previous ref
was detected, it will be aborted and a new instance will be set up for
the next run. However, while the logic was aborting previous instances
as expected, it was failing to instantiate a new one.
  • Loading branch information
jacobsfletch authored Jan 2, 2025
1 parent b2042c5 commit abb51b9
Showing 1 changed file with 14 additions and 5 deletions.
19 changes: 14 additions & 5 deletions packages/ui/src/utilities/abortAndIgnore.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,19 +8,28 @@ export function abortAndIgnore(abortController: AbortController) {
}
}

/**
* Use this function when an effect is triggered multiple times over and you want to cancel the previous effect.
* It will abort the previous effect and create a new AbortController for the next effect.
* Important: You must also _reset_ the `abortControllerRef` after the effect is done, otherwise the next effect will be aborted immediately.
* For example, run `abortControllerRef.current = null` in a `finally` block or after an awaited promise.
* @param abortControllerRef
* @returns {AbortController}
*/
export function handleAbortRef(
abortControllerRef: React.RefObject<AbortController>,
): AbortController {
const newController = new AbortController()

if (abortControllerRef.current) {
try {
abortControllerRef.current.abort()
abortControllerRef.current = null
} catch (_err) {
// swallow error
}
} else {
const controller = new AbortController()
abortControllerRef.current = controller
return controller
}

abortControllerRef.current = newController

return newController
}

0 comments on commit abb51b9

Please sign in to comment.