useRequest

function useRequest<T>(source, options?): RequestResult<T>;

Fire a one-shot request on mount and re-fire each time source changes identity or refresh() is called. Returns reactive state tracking the call's lifecycle.

Two ways to pass the work:

  • A ReactiveActionSource — the { reactiveStore() } duck-type satisfied by PendingRpcRequest.
  • An async function (signal: AbortSignal) => Promise<T> — wrap any one-shot async source (a fetch, a third-party SDK call, etc). Most general shape.

Pass null to disable; the result reports status: 'disabled'.

Memoize the input (useMemo for a source, useCallback for a function) keyed on whatever inputs it depends on.

Type Parameters

Type ParameterDescription
TThe value the underlying request resolves to.

Parameters

ParameterType
source| ReactiveActionSource<T> | ((signal) => Promise<T>) | null
options?UseRequestOptions

Returns

RequestResult<T>

Example

function LatestBlockhash() {
    const client = useClient<ClientWithRpc<GetLatestBlockhashApi>>();
    const source = useMemo(() => client.rpc.getLatestBlockhash(), [client]);
    const { data, error, refresh } = useRequest(source, {
        getAbortSignal: () => AbortSignal.timeout(5_000),
    });
    if (error) return <button onClick={refresh}>Retry</button>;
    return <p>{data ? `Blockhash: ${data.value.blockhash}` : 'Loading…'}</p>;
}
 
// Function shape — wraps an arbitrary async call:
function Profile({ userId }: { userId: string }) {
    const fetcher = useCallback(
        (signal: AbortSignal) => fetch(`/api/users/${userId}`, { signal }).then(r => r.json()),
        [userId],
    );
    const { data, error, refresh } = useRequest(fetcher);
    if (error) return <button onClick={refresh}>Retry</button>;
    return <p>{data ? data.name : 'Loading…'}</p>;
}

See

On this page