On first render, as well as whenever the deps have changed,
this React hook returns { state: 'notStarted' }
as well as a trigger function with a fresh object identity.
The trigger function maintains its object identity
when the deps remain unchanged.
The trigger function can then be called in order to run fn,
updating the state with fn's outputs when the promise resolves.
Such an update ensures a fresh render (by updating the React state).
The trigger is a no-op if the state is already loading or resolved,
but does launch fn again if the state is rejected.
fn receives an AbortSignal that is aborted
whenever the output of fn is no longer needed
because the deps have changed.
useAsyncWithTrigger prevents race conditions
when requests resolve in a different order
to that which they were triggered in:
Initial deps are, say, line=42.
Trigger called, Request 1 is sent.
Deps change to line=90, new trigger called, Request 2 is sent.
Request 2 returns with diags=[].
Request 1 returns with diags=['error'].
Without useAsyncWithTrigger we would now return the diagnostics for line 42
even though we're at line 90.
Must be used at the top-level like other React hooks.
On first render, as well as whenever the deps have changed, this React hook returns
{ state: 'notStarted' }as well as a trigger function with a fresh object identity. The trigger function maintains its object identity when the deps remain unchanged.The trigger function can then be called in order to run
fn, updating the state withfn's outputs when the promise resolves. Such an update ensures a fresh render (by updating the React state). The trigger is a no-op if the state is alreadyloadingorresolved, but does launchfnagain if the state isrejected.fnreceives anAbortSignalthat is aborted whenever the output offnis no longer needed because the deps have changed.useAsyncWithTriggerprevents race conditions when requests resolve in a different order to that which they were triggered in:Without
useAsyncWithTriggerwe would now return the diagnostics for line 42 even though we're at line 90.Must be used at the top-level like other React hooks.