MCPcopy Create free account
hub / github.com/RtlZeroMemory/Rezi / useAsync

Function useAsync

packages/core/src/widgets/hooks/data.ts:327–368  ·  view source on GitHub ↗
(
  ctx: AsyncHookContext,
  task: () => Promise<T>,
  deps: readonly unknown[],
)

Source from the content-addressed store, hash-verified

325 * - Ignores stale completions from older dependency runs
326 */
327export 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.

Callers 2

crew.tsFile · 0.90

Calls 1

resolveMethod · 0.80

Tested by

no test coverage detected