API Reference
useAsync

useAsync

useAsync is a powerful utility for managing the state of asynchronous operations. It simplifies handling async functions, providing an easy way to track their execution status and either manually or immediately invoke them. It simplifies the process of tracking and executing asynchronous functions while providing clear states for loading, errors, and data.

Installation

  1. Make sure you have @ridgehkr/useful installed in your application. If not, you can get started by following the installation instructions.

  2. Import useAsync into your component.

import { useAsync } from '@ridgehkr/useful'

Usage

The primary purpose of useAsync is to manage the execution state of an asynchronous function. It returns an object that provides information about the state of it and a function to execute it if not immediately invoked.

const { data, loading, error, run } = useAsync(asyncFunction)

Where:

  • data holds the result of the async function when it completes successfully or null if it hasn't been executed yet.
  • loading is a boolean indicating whether the async function is currently running.
  • error contains any error that occurs during the async function execution or null if no errors occurred.
  • run is a function that triggers the execution of the async function.

See the API Reference for more details on these return values.

Immediate Execution

By default, the async function passed to useAsync is executed immediately upon component render. You can prevent this behavior by passing false as the second argument to the hook:

// The async function will not run immediately. Manually invoke it using the `run` function.
const { data, loading, error, run } = useAsync(asyncFunction, false)

Setting this argument to false means the async function will not run immediately, allowing you to trigger it manually using the run function.

Example 1: Immediate Execution

AsyncHandler.jsx
import { useAsync } from '@ridgehkr/useful'
 
const asyncFunction = async (): Promise<string> => {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve('Done!')
    }, 2000)
  })
}
 
function AsyncHandler() {
  const { data, loading, error } = useAsync<string>(asyncFunction, true)
 
  return (
    <div className={style.demo}>
      <header className={style.header}>
        <h1>useAsync</h1>
      </header>
 
      {loading && <p>Waiting 2 seconds…</p>}
 
      {error?.message && <p>Error: {error.message}</p>}
 
      {data && <p>{data}</p>}
    </div>
  )
}

Example 2: Manual Execution

The example has been slightly altered to demonstrate manual execution of the async function argument. Because the immediate flag is false, the asynchronous function asyncFunction will not run immediately upon component render. Instead, it will wait for the run function to be called when the button is clicked:

AsyncHandler.jsx
import React from 'react'
import { useAsync } from '@ridgehkr/useful'
 
const asyncFunction = async (): Promise<string> => {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve('Done!')
    }, 2000)
  })
}
 
function HookDemo() {
  const { data, loading, error, run } = useAsync<string>(asyncFunction, false)
 
  return (
    <div className={style.demo}>
      <header className={style.header}>
        <h1>useAsync</h1>
      </header>
 
      <button onClick={run}>Run asyncFunction</button>
 
      {loading && <p>Waiting 2 seconds…</p>}
 
      {error?.message && <p>Error: {error.message}</p>}
 
      {data && <p>{data}</p>}
    </div>
  )
}

API Reference

Parameters

useAsync accepts two parameters:

PropertyTypeDescription
asyncFunction() => Promise<T>The asyncronous function to track the status of
immediatebooleanWhether the async function should run immediately upon component render

Return Value

The hook returns an object with the following properties:

PropertyTypeDescription
datanumberThe return value of the asynchronous function
loadingbooleanWhether or not the asynchronous function has been executed, but not resolved
errorErrorAny error that occurs during the execution of the asynchronous function
runvoidA function that triggers the execution of the asynchronous function