Data APIs

createAsync

Edit this page

The createAsync primitive manages asynchronous data fetching by tracking the result of a promise-returning function.


Import

import { createAsync } from "@solidjs/router";

Type

function createAsync<T>(
fn: (prev: T) => Promise<T>,
options: {
name?: string;
initialValue: T;
deferStream?: boolean;
}
): AccessorWithLatest<T>;
function createAsync<T>(
fn: (prev: T | undefined) => Promise<T>,
options?: {
name?: string;
initialValue?: T;
deferStream?: boolean;
}
): AccessorWithLatest<T | undefined>;

Parameters

fetcher

  • Type: (prev: T | undefined) => Promise<T>
  • Required: Yes

An asynchronous function or a function that returns a Promise. The resolved value of this Promise is what createAsync tracks. This function is reactive and will automatically re-execute if any of its dependencies change.

options

  • Type: { name?: string; initialValue?: T; deferStream?: boolean; }
  • Required: No

An object for configuring the primitive. It has the following properties:

name

  • Type: string
  • Required: No

A name for the resource, used for identification in debugging tools like Solid Debugger.

initialValue

  • Type: T
  • Required: No

The initial value of the returned signal before the fetcher finishes executing.

deferStream

  • Type: boolean
  • Required: No

If true, streaming will be deferred until the fetcher finishes executing.


Return value

createAsync returns a derived signal that contains the resolved value of the fetcher.

While the fetcher is executing for the first time, unless an initialValue is specified, the signal's value is undefined.


Examples

Basic usage

import { createAsync, query } from "@solidjs/router";
const getUserQuery = query(async (id: string) => {
// ... Fetches the user from the server.
}, "user");
function UserProfile() {
const user = createAsync(() => getUserQuery());
return <p>{user()?.name}</p>;
}

Handling loading and errors

import { Suspense, ErrorBoundary, For } from "solid-js";
import { createAsync, query } from "@solidjs/router";
const getUserQuery = query(async (id: string) => {
// ... Fetches the user from the server.
}, "user");
function UserProfile() {
const user = createAsync(() => getUserQuery());
return (
<ErrorBoundary fallback={<p>Could not fetch user data.</p>}>
<Suspense fallback={<p>Loading user...</p>}>
<p>{user()!.name}</p>
</Suspense>
</ErrorBoundary>
);
}
Report an issue with this page