Skip to content

Async dataNew in 7.2

Turn asynchronous work into signals, and show a fallback while it loads.

docs/learn/async-data.md
moduleXote.Resourceboundarysrc/Resource.resientryxote/resourceversion7.2.0
Raw Markdown

A resource turns asynchronous work, like a fetch, into a signal. View.Suspense shows a fallback while the resources below it load for the first time.

Info: A resource is a Signal.t of its loading state. Read it with Signal.get like any other signal.

Create a resource

Resource.make takes a function that returns a promise, and starts it right away. Here Api.getUser stands for your own function that returns promise<user>; Fetching data shows how to write one.

1let userId = Signal.make("1")
2
3let user = Resource.make(async () => {
4 let id = Signal.get(userId) // a dependency: read before the first await
5 await Api.getUser(id)
6})

The function runs in an effect. The signals it reads before its first await are its dependencies: change userId and the resource fetches again. Reads after an await aren't tracked.

Read its state

A resource holds one of four states:

  • Pending: fetching with no value yet, on the first fetch or after a failure.
  • Ready(value): the latest fetch settled with value.
  • Refreshing(value): fetching again, with the previous value kept.
  • Failed(exn): the latest fetch threw or rejected.
1module UserName = {
2 @xote.component
3 let make = () =>
4 <p>
5 {switch Signal.get(user) {
6 | Pending => "Loading..."
7 | Ready(user) | Refreshing(user) => user.name
8 | Failed(_) => "Could not load the user"
9 }}
10 </p>
11}

Resource.value returns the value a state carries, if any, and Resource.isLoading tells whether a fetch is in flight.

Refetch or set the value

Resource.refetch fetches again with the same dependencies. Resource.mutate sets the value directly, which is useful for optimistic updates, and drops any fetch in flight.

1<button onClick={_ => Resource.refetch(user)}> {"Reload"} </button>

Only the latest fetch can settle the state. If the user switches from one id to another and the first response arrives last, it's ignored.

Handle errors

A failed fetch is a state like any other. To hand it to a View.ErrorBoundary instead, throw it where the state is read:

1switch Signal.get(user) {
2| Failed(exn) => throw(exn)
3| state => ...
4}

Suspense

To show a fallback while loading, wrap the components that create resources in View.Suspense:

1<View.Suspense fallback={<p> {"Loading..."} </p>}>
2 <Profile id />
3 <Posts id />
4</View.Suspense>

The fallback shows until every resource created below the suspense has loaded once. The children render straight away, hidden, so their fetches start at once and their state survives the wait. Their refs and onMount callbacks wait until they're shown.

Suspense rules

  • A resource suspends the nearest Suspense above the component that created it, wherever it is read.
  • A resource counts once. A later fetch shows as Refreshing and never brings the fallback back.
  • Suspenses nest. The nearest one waits, and an inner subtree that is ready stays hidden while an outer suspense still waits.
  • Removing a component releases its resources: a fetch in flight is dropped, and a suspense waiting for it stops waiting.

Server rendering

During a server render (SSR.renderToString) nothing is awaited: no fetch starts, and Suspense renders its fallback. A resource created outside a render, at module level in a server process, isn't covered and does fetch, so create resources in components. Hydration then renders the children in the browser, where the resources fetch.

To handle failures with a boundary, see error boundaries. For loading, refetching and search patterns, see Fetching data.

Summary

A resource (Resource.make) is a signal of the loading state of an async function: Signal.t<Resource.state<'a>>. The fetch runs inside an effect, so every signal it reads (tracked) before its first await is a dependency, and a change to any dependency starts a new fetch. Only the latest fetch can settle the state; an earlier one that resolves late is ignored. View.Suspense shows a fallback until the resources created below it settle once; a Failed state can be thrown to a View.ErrorBoundary. The rule that matters most: read every input signal before the first await, or changes to it will not refetch.

Availability

ItemValue
ModulesResource, View.Suspense (plus View.ErrorBoundary for failures)
Import / entryxote (with -open Xote), or xote/resource for Resource alone
First stable version7.2.0 (new)
Statusnew in 7.2.0 (Resource, View.Suspense and View.ErrorBoundary all first appear in 7.2.0)
PPX requiredNo. Resource and View.Suspense work with @jsx.component; examples use @xote.component

Rules

  1. Resource.make(fetch) creates the state signal with value Pending and immediately runs fetch inside an effect (unless a server render is in progress, see rule 13).
  2. The dependencies of a resource are exactly the signals read (tracked) while fetch() runs synchronously, that is, up to its first await. Reads after an await are not dependencies.
  3. When a dependency changes, the effect re-runs: the state moves to Refreshing(previousValue) if it held a value (Ready or Refreshing), otherwise to Pending (from Pending or Failed), and fetch is called again.
  4. Each fetch gets a version number. A fetch settles the state only if no later fetch, mutate or disposal has happened since it started. Late results of superseded fetches are dropped silently.
  5. A fetch that returns a rejected promise, or throws synchronously, settles as Failed(exn). A failure that happens while rendering the settled value is not a fetch failure and does not produce Failed.
  6. Resource.refetch(r) re-runs the fetch with the same dependencies (same transitions as rule 3). It is a no-op for a resource created during a server render.
  7. Resource.mutate(r, v) sets Ready(v) immediately and invalidates any fetch in flight (its result is dropped). The next dependency change or refetch fetches again.
  8. A resource created while a component renders is owned by that component: disposing the component drops the fetch in flight (its result is ignored) and, if a View.Suspense was waiting for it, ends that wait.
  9. A resource created outside any render (module level, event handler) has no owner and lives for the rest of the program.
  10. A resource suspends the nearest View.Suspense above the component that created it, regardless of where its state is read.
  11. A resource counts toward its suspense only once: the suspense waits until the first settle (Ready, Failed, or mutate). Later fetches show as Refreshing and never bring the fallback back.
  12. Nested suspenses: the nearest one waits for its own resources; a ready inner subtree stays hidden while an outer suspense still waits.
  13. During SSR.renderToString / SSR.renderDocument no fetch starts and the resource stays Pending forever on the server. View.Suspense renders its fallback into the HTML. A resource created at module level in a server process is not inside a render, so it does fetch.
  14. To send a failure to an error boundary, throw it where the state is read inside the render tree: | Failed(error) => throw(error) in a reactive leaf or region.

State machine

FromEventTo
(created)Resource.make (client)Pending, fetch starts
Pendingfetch resolves with vReady(v)
Pendingfetch rejects or throws eFailed(e)
Ready(v)dependency change or refetchRefreshing(v), fetch starts
Refreshing(v)fetch resolves with wReady(w)
Refreshing(v)fetch rejects eFailed(e) (the previous value is not kept)
Failed(e)dependency change or refetchPending, fetch starts
anymutate(r, w)Ready(w), in-flight fetch dropped
anyowner disposedunchanged; in-flight fetch dropped

API

NameSignatureBehaviour
Resource.statePending, Ready('a), Refreshing('a), Failed(exn)Where a resource stands (see the state machine).
Resource.tSignal.t<state<'a>>A resource is a signal: read it with Signal.get (tracked) or Signal.peek.
Resource.make(unit => promise<'a>) => t<'a>Creates the resource and starts the first fetch (client only).
Resource.refetcht<'a> => unitFetches again with the same dependencies.
Resource.mutate(t<'a>, 'a) => unitSets Ready(value) now, drops any fetch in flight.
Resource.valuestate<'a> => option<'a>Some(v) for Ready(v) and Refreshing(v), None otherwise.
Resource.isLoadingstate<'a> => booltrue for Pending and Refreshing.
View.Suspenseprops fallback?: node, children?: nodeShows fallback until every resource created below has settled once.
View.ErrorBoundaryprops fallback: (exn, unit => unit) => node, onError?: exn => unit, children?: nodeCatches render/update failures below; fallback gets the error and a reset function.

Note that Resource.value and Resource.isLoading take a state, not a resource: write Resource.value(Signal.get(r)) or Signal.get(r)->Resource.value.

Patterns

Use when a component loads data that depends on a prop or a signal: create the resource in the component and switch over its state.

1module UserCard = {
2 @xote.component
3 let make = (~userId: Signal.t<string>) => {
4 let user = Resource.make(() => Api.getUser(Signal.get(userId)))
5 <p>
6 {switch Signal.get(user) {
7 | Pending => "Loading…"
8 | Ready(u) | Refreshing(u) => u.name
9 | Failed(_) => "Could not load the user."
10 }}
11 </p>
12 }
13}

Use when loading and failure states should live outside the component: a View.Suspense for the first load and a View.ErrorBoundary for failures. The component that creates the resource MUST be inside the Suspense.

1module UserName = {
2 @xote.component
3 let make = (~userId: Signal.t<string>) => {
4 let user = Resource.make(() => Api.getUser(Signal.get(userId)))
5 <h2>
6 {switch Signal.get(user) {
7 | Failed(error) => throw(error)
8 | Ready(u) | Refreshing(u) => u.name
9 | Pending => ""
10 }}
11 </h2>
12 }
13}
14
15module Profile = {
16 @xote.component
17 let make = (~userId: Signal.t<string>) =>
18 <View.ErrorBoundary
19 fallback={(_error, retry) =>
20 <div>
21 <p> {"Could not load the user."} </p>
22 <button onClick={_ => retry()}> {"Try again"} </button>
23 </div>}>
24 <View.Suspense fallback={<p> {"Loading…"} </p>}>
25 <UserName userId />
26 </View.Suspense>
27 </View.ErrorBoundary>
28}

retry re-creates everything inside the boundary, so UserName runs again and creates a new resource, which fetches again.

Use when the user edits loaded data: update optimistically with mutate, then refetch after the save. Dim stale values with Resource.isLoading.

1module EditableName = {
2 @xote.component
3 let make = (~userId: Signal.t<string>) => {
4 let user = Resource.make(() => Api.getUser(Signal.get(userId)))
5 let rename = name => {
6 Signal.peek(user)
7 ->Resource.value
8 ->Option.forEach(u => Resource.mutate(user, {...u, name}))
9 Api.saveName(Signal.peek(userId), name)
10 ->Promise.thenResolve(() => Resource.refetch(user))
11 ->ignore
12 }
13 <div>
14 <p class={Resource.isLoading(Signal.get(user)) ? "dim" : ""}>
15 {Signal.get(user)->Resource.value->Option.mapOr("", u => u.name)}
16 </p>
17 <button onClick={_ => rename("Grace")}> {"Rename"} </button>
18 <button onClick={_ => Resource.refetch(user)}> {"Reload"} </button>
19 </div>
20 }
21}

Use when several components share one piece of remote state for the life of the page: create the resource at module level. It has no owner and is never disposed.

1let currentUserId = Signal.make("1")
2let currentUser = Resource.make(() => Api.getUser(Signal.get(currentUserId)))

Anti-patterns

Reading an input after the first await.

1let wrong = Resource.make(async () => {
2 let q = Signal.get(query)
3 await Promise.resolve()
4 await searchApi(q, Signal.get(page)) // page read after an await: not a dependency
5})

Symptom: changing page does nothing; only changing query refetches. Correct: read every input first, then start the async work.

1let right = Resource.make(() => {
2 let q = Signal.get(query)
3 let p = Signal.get(page)
4 searchApi(q, p)
5})

Why: dependencies are recorded only while fetch runs synchronously (rule 2).

Creating the resource above the Suspense that should wait for it.

1@xote.component
2let make = (~userId) => {
3 let user = Resource.make(() => Api.getUser(Signal.get(userId)))
4 <View.Suspense fallback={<p> {"Loading…"} </p>}>
5 <UserView user />
6 </View.Suspense>
7}

Symptom: the fallback never shows; UserView renders Pending itself. Correct: create the resource inside a component rendered under the Suspense (see the UserName pattern). Why: a resource suspends the nearest suspense above the component that created it (rule 10), and here there is none.

Swallowing failures under an error boundary.

1{switch Signal.get(user) {
2| Failed(_) => ""
3| Ready(u) | Refreshing(u) => u.name
4| Pending => ""
5}}

Symptom: on failure the UI is blank and the boundary's fallback never appears. Correct: | Failed(error) => throw(error). Why: an error boundary only sees errors thrown while rendering (rule 14); a resource never throws on its own.

Creating a resource inside a reactive region or a list row render function that re-runs.

Symptom: a new fetch on every re-run of the region (for example every time an if condition changes, or every View.tracked re-run), and earlier resources are disposed mid-flight. Correct: create the resource in a component body (runs once) or at module level, and read it in the region.

Calling Resource.make from an event handler.

Symptom: a resource with no owner per click; nothing disposes them, and nothing reads the old ones. Correct: create the resource once (component body or module level) and call Resource.refetch or change a dependency signal from the handler.

Edge cases

  • Refreshing → Failed drops the previous value: Resource.value returns None after a failed refresh.
  • mutate while Pending under a Suspense ends the suspense wait (the resource has settled for the suspense's purposes).
  • Signal equality: every settle writes a new Ready(v) value, so readers are notified even when v is structurally equal to the previous value.
  • View.Suspense renders its children immediately, inside a wrapper div with display: none while waiting and display: contents after; their refs and View.onMount callbacks are held until the children are shown. CSS child selectors see these wrappers.
  • View.ErrorBoundary also renders a <div style="display: contents"> around its subtree.
  • Cancellation: there is none. A superseded fetch keeps running; only its result is ignored. Pass an AbortController signal yourself if the request must be aborted.
  • Ownership: a resource created in a component that is later removed stops affecting state; a resource at module level keeps re-fetching on dependency changes forever.

SSR and hydration

  • In a server render no fetch starts: a component's resource is Pending in the HTML, and View.Suspense writes its fallback.
  • On the client, the Suspense region is rendered again rather than adopted, so its children mount and their resources fetch in the browser.
  • To ship data with the HTML instead, load it on the server before rendering, put it in a signal, register that signal with SSRState.sync after it holds the data, and read the signal (not a resource) in the component. See /docs/advanced/ssr.
  • A module-level resource in a server process fetches (it is not created during a render); its result is not serialized unless you transfer it through SSRState yourself.

Verify

  • Type errors to expect: passing a resource where a state is expected (Resource.value(user)) fails to compile; write Resource.value(Signal.get(user)). A switch missing Refreshing is a non-exhaustive match warning.
  • Minimal jsdom test: mount a component whose fetch awaits a promise you control; assert the text is Pending (or the Suspense fallback) before resolving and the value after one macrotask (await new Promise(r => setTimeout(r, 0))).
  • Dependency check: change a signal read after an await and assert that no new fetch started (count calls in the fetch function).
  • Server check: SSR.renderToString of a component with a resource contains its Pending branch (or the Suspense fallback) and the fetch function is never called.
  • /docs/learn/effects — resources are built on effects; the same tracking rules apply.
  • /docs/learn/lifecycle#agent-rules — View.ErrorBoundary rules (what it catches, reset).
  • /docs/guides/fetching-data — recipes: search as you type, refetch on route change.
  • /docs/advanced/ssr — transferring loaded data with SSRState.
  • /docs/learn/signals — reading a resource is reading a signal.