Commit 8ff18e2
authored
Fix useAbortableAsync race condition (#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.1 parent 1ec6245 commit 8ff18e2
File tree
1 file changed
+10
-1
lines changed- x-pack/solutions/observability/packages/utils_browser/hooks
1 file changed
+10
-1
lines changedLines changed: 10 additions & 1 deletion
| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
58 | 58 | | |
59 | 59 | | |
60 | 60 | | |
| 61 | + | |
| 62 | + | |
| 63 | + | |
| 64 | + | |
61 | 65 | | |
62 | 66 | | |
63 | 67 | | |
64 | 68 | | |
65 | 69 | | |
66 | 70 | | |
| 71 | + | |
67 | 72 | | |
68 | 73 | | |
69 | 74 | | |
| |||
78 | 83 | | |
79 | 84 | | |
80 | 85 | | |
| 86 | + | |
81 | 87 | | |
82 | 88 | | |
83 | 89 | | |
84 | 90 | | |
85 | | - | |
| 91 | + | |
| 92 | + | |
| 93 | + | |
| 94 | + | |
86 | 95 | | |
87 | 96 | | |
88 | 97 | | |
| |||
0 commit comments