Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Fix useAbortableAsync race condition (elastic#207365)
`useAbortableAsync` can easily get confused about the current state - e.g. when a previous invocation gets aborted and a new one is started at the same time, the `loading` state gets set to false _after_ the next invocation got started, so it's false for the time it's running:  You can see that while typing, the old slow request is aborted properly, but the `loading` state gets lost and the abort error from the last invocation is still set even though a new request is running already. This is not the only possible issue that could happen here - e.g. if the promise chain throws too late, an unrelated error could be set in the error handling logic, which is not related to the currently running `fn`. This is hard to fix because as the hook does not control the `fn`, it does not know at which point it resolves, even after a new invocation was started already. The abort signal asks the `fn` nicely to throw with an abort error, but it can't be controlled when that happens. This PR introduces a notion of the current "generation" and only accepts state updates from the most recent one. With this, the new invocation correctly sets the loading state after the abort - what happens to the old promise chain after the abort can't affect the state anymore:  I'm not sure whether this is the best way to resolve this issue, but I couldn't come up with a better way. Happy to adjust, but I think we need a solution that doesn't assume any special behavior of the passed in `fn`, otherwise this helper will always be super brittle. (cherry picked from commit 8ff18e2)
- Loading branch information