Async dataNew in 7.2
Turn asynchronous work into signals, and show a fallback while it loads.
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.tof its loading state. Read it withSignal.getlike 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")23let user = Resource.make(async () => {4 let id = Signal.get(userId) // a dependency: read before the first await5 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 withvalue.Refreshing(value): fetching again, with the previousvaluekept.Failed(exn): the latest fetch threw or rejected.
1module UserName = {2 @xote.component3 let make = () =>4 <p>5 {switch Signal.get(user) {6 | Pending => "Loading..."7 | Ready(user) | Refreshing(user) => user.name8 | 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
Suspenseabove the component that created it, wherever it is read. - A resource counts once. A later fetch shows as
Refreshingand 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
| Item | Value |
|---|---|
| Modules | Resource, View.Suspense (plus View.ErrorBoundary for failures) |
| Import / entry | xote (with -open Xote), or xote/resource for Resource alone |
| First stable version | 7.2.0 (new) |
| Status | new in 7.2.0 (Resource, View.Suspense and View.ErrorBoundary all first appear in 7.2.0) |
| PPX required | No. Resource and View.Suspense work with @jsx.component; examples use @xote.component |
Rules
Resource.make(fetch)creates the state signal with valuePendingand immediately runsfetchinside an effect (unless a server render is in progress, see rule 13).- The dependencies of a resource are exactly the signals read (tracked) while
fetch()runs synchronously, that is, up to its firstawait. Reads after anawaitare not dependencies. - When a dependency changes, the effect re-runs: the state moves to
Refreshing(previousValue)if it held a value (ReadyorRefreshing), otherwise toPending(fromPendingorFailed), andfetchis called again. - Each fetch gets a version number. A fetch settles the state only if no later fetch,
mutateor disposal has happened since it started. Late results of superseded fetches are dropped silently. - 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 produceFailed. 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.Resource.mutate(r, v)setsReady(v)immediately and invalidates any fetch in flight (its result is dropped). The next dependency change orrefetchfetches again.- 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.Suspensewas waiting for it, ends that wait. - A resource created outside any render (module level, event handler) has no owner and lives for the rest of the program.
- A resource suspends the nearest
View.Suspenseabove the component that created it, regardless of where its state is read. - A resource counts toward its suspense only once: the suspense waits until the first settle (
Ready,Failed, ormutate). Later fetches show asRefreshingand never bring the fallback back. - Nested suspenses: the nearest one waits for its own resources; a ready inner subtree stays hidden while an outer suspense still waits.
- During
SSR.renderToString/SSR.renderDocumentno fetch starts and the resource staysPendingforever on the server.View.Suspenserenders itsfallbackinto the HTML. A resource created at module level in a server process is not inside a render, so it does fetch. - 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
| From | Event | To |
|---|---|---|
| (created) | Resource.make (client) | Pending, fetch starts |
Pending | fetch resolves with v | Ready(v) |
Pending | fetch rejects or throws e | Failed(e) |
Ready(v) | dependency change or refetch | Refreshing(v), fetch starts |
Refreshing(v) | fetch resolves with w | Ready(w) |
Refreshing(v) | fetch rejects e | Failed(e) (the previous value is not kept) |
Failed(e) | dependency change or refetch | Pending, fetch starts |
| any | mutate(r, w) | Ready(w), in-flight fetch dropped |
| any | owner disposed | unchanged; in-flight fetch dropped |
API
| Name | Signature | Behaviour |
|---|---|---|
Resource.state | Pending, Ready('a), Refreshing('a), Failed(exn) | Where a resource stands (see the state machine). |
Resource.t | Signal.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.refetch | t<'a> => unit | Fetches again with the same dependencies. |
Resource.mutate | (t<'a>, 'a) => unit | Sets Ready(value) now, drops any fetch in flight. |
Resource.value | state<'a> => option<'a> | Some(v) for Ready(v) and Refreshing(v), None otherwise. |
Resource.isLoading | state<'a> => bool | true for Pending and Refreshing. |
View.Suspense | props fallback?: node, children?: node | Shows fallback until every resource created below has settled once. |
View.ErrorBoundary | props fallback: (exn, unit => unit) => node, onError?: exn => unit, children?: node | Catches 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.component3 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.name9 | 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.component3 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.name9 | Pending => ""10 }}11 </h2>12 }13}1415module Profile = {16 @xote.component17 let make = (~userId: Signal.t<string>) =>18 <View.ErrorBoundary19 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.component3 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.value8 ->Option.forEach(u => Resource.mutate(user, {...u, name}))9 Api.saveName(Signal.peek(userId), name)10 ->Promise.thenResolve(() => Resource.refetch(user))11 ->ignore12 }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 dependency5})
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.component2let 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.name4| 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 → Faileddrops the previous value:Resource.valuereturnsNoneafter a failed refresh.mutatewhilePendingunder aSuspenseends 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 whenvis structurally equal to the previous value. View.Suspenserenders its children immediately, inside a wrapperdivwithdisplay: nonewhile waiting anddisplay: contentsafter; their refs andView.onMountcallbacks are held until the children are shown. CSS child selectors see these wrappers.View.ErrorBoundaryalso 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
AbortControllersignal 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
Pendingin the HTML, andView.Suspensewrites itsfallback. - On the client, the
Suspenseregion 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.syncafter 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
SSRStateyourself.
Verify
- Type errors to expect: passing a resource where a state is expected (
Resource.value(user)) fails to compile; writeResource.value(Signal.get(user)). AswitchmissingRefreshingis 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
awaitand assert that no new fetch started (count calls in the fetch function). - Server check:
SSR.renderToStringof a component with a resource contains itsPendingbranch (or the Suspense fallback) and the fetch function is never called.
Related
/docs/learn/effects— resources are built on effects; the same tracking rules apply./docs/learn/lifecycle#agent-rules—View.ErrorBoundaryrules (what it catches,reset)./docs/guides/fetching-data— recipes: search as you type, refetch on route change./docs/advanced/ssr— transferring loaded data withSSRState./docs/learn/signals— reading a resource is reading a signal.