Skip to content

useAsync

This hook simplifies the execution of an async function by returning its states and results.

Parameters

Return Values

NameTypeDescription
datacallback return typeresolved data from the function.
isPendingBooleanthe loading state.
callbackFnuctionthe async callback function.
errorUnknowncached error if it exists.

Example Usage

tsx
import { useAsync } from 'react-pre-hooks';

const getData = (ms: number) => {
  return new Promise<string>(res => setTimeout(() => res('Resolved!'), ms));
};

export default function Example() {
  const { data, isPending, callback } = useAsync(async () => {
    return await getData(2200);
  });

  return (
    <main>
      <div>{isPending ? 'Loading...' : data ?? 'No data.'}</div>
      <button onClick={callback}>Start</button>
    </main>
  );
}
import { useAsync } from 'react-pre-hooks';

const getData = (ms: number) => {
  return new Promise<string>(res => setTimeout(() => res('Resolved!'), ms));
};

export default function Example() {
  const { data, isPending, callback } = useAsync(async () => {
    return await getData(2200);
  });

  return (
    <main>
      <div>{isPending ? 'Loading...' : data ?? 'No data.'}</div>
      <button onClick={callback}>Start</button>
    </main>
  );
}

Released under the MIT License.