( ctx: AsyncHookContext, task: () => Promise<T>, deps: readonly unknown[], )
| 325 | * - Ignores stale completions from older dependency runs |
| 326 | */ |
| 327 | export function useAsync<T>( |
| 328 | ctx: AsyncHookContext, |
| 329 | task: () => Promise<T>, |
| 330 | deps: readonly unknown[], |
| 331 | ): UseAsyncState<T> { |
| 332 | const [data, setData] = ctx.useState<T | undefined>(undefined); |
| 333 | const [loading, setLoading] = ctx.useState<boolean>(true); |
| 334 | const [error, setError] = ctx.useState<unknown>(undefined); |
| 335 | const runIdRef = ctx.useRef(0); |
| 336 | |
| 337 | ctx.useEffect(() => { |
| 338 | let cancelled = false; |
| 339 | runIdRef.current += 1; |
| 340 | const runId = runIdRef.current; |
| 341 | |
| 342 | setLoading(true); |
| 343 | setError(undefined); |
| 344 | |
| 345 | Promise.resolve() |
| 346 | .then(() => task()) |
| 347 | .then((nextData) => { |
| 348 | if (cancelled || runIdRef.current !== runId) return; |
| 349 | setData(nextData); |
| 350 | setLoading(false); |
| 351 | }) |
| 352 | .catch((nextError) => { |
| 353 | if (cancelled || runIdRef.current !== runId) return; |
| 354 | setError(nextError); |
| 355 | setLoading(false); |
| 356 | }); |
| 357 | |
| 358 | return () => { |
| 359 | cancelled = true; |
| 360 | }; |
| 361 | }, deps); |
| 362 | |
| 363 | return { |
| 364 | data, |
| 365 | loading, |
| 366 | error, |
| 367 | }; |
| 368 | } |
| 369 | |
| 370 | /** |
| 371 | * Subscribe to an async iterable and re-render on each value. |
no test coverage detected