usePromise
Similar to useAsync, but returns a promise that can be used with <Derive> for fine-grained reactivity and SSR support.
usePromise creates an AbortController
and passes the controller's abort signal to the async function.
When usePromise re-runs, the signal is aborted, making it easy to cancel a running async function or request.
The promise returned by usePromise is designed to work with <Derive />, which provides automatic
handling of loading states, stale data, and SSR streaming.
Example
import { usePromise, Derive } from "kiru"
type ProductsResponse = {
products: Array<{
id: number
title: string
}>
}
function Page() {
const products = usePromise<ProductsResponse>(async (signal) => {
await new Promise((resolve) => setTimeout(resolve, 500))
const response = await fetch("https://dummyjson.com/products", { signal })
if (!response.ok) throw new Error(response.statusText)
return await response.json()
}, [])
return (
<Derive from={products} fallback={<div>Loading...</div>}>
{(data, isStale) => (
<ul className={isStale ? "opacity-50" : ""}>
{data.products.map((product) => (
<li key={product.id}>{product.title}</li>
))}
</ul>
)}
</Derive>
)
}