useAsync

Similar to useEffect, but runs an async function and returns a tuple containing a .

Example

import { useState, useAsync } from "kaioken"

export function UseAsyncExample() {
  const [productId, setProductId] = useState(1)

  // Use useAsync to run an async function whenever the productId changes
  const [data, loading, error] = useAsync(async () => {
    return (await fetch(`https://dummyjson.com/products/${productId}`)).json()
  }, [productId])

  return (
    <div>
      <button onclick={() => setProductId((prev) => prev + 1)}>Next</button>
      {data ? (
        <ProductCard product={data} />
      ) : loading ? (
        <Spinner />
      ) : (
        <p>{error.message}</p>
      )}
    </div>
  )
}

Related