Fetching dataNew in 7.2
Load data, show loading and error states, refetch when inputs change, and search as people type.
These recipes cover the data loading most screens need: a first load, loading and error states, refetching when something changes, search as you type, and saving changes. They all build on resources, so read that page first if Resource.make is new to you.
Try it
Type in the box below. The search waits for a short pause in typing, then asks a pretend server that takes 400ms to answer. While a new search runs, the previous results stay on screen, dimmed.
1let fruits = [2 "Apple", "Apricot", "Banana", "Blackberry", "Blueberry", "Cherry", "Grape", "Lemon",3 "Lime", "Mango", "Orange", "Peach", "Pear", "Plum", "Raspberry", "Strawberry",4]56// A pretend server: answers after 400ms.7let searchFruits = (query: string): promise<array<string>> =>8 Promise.make((resolve, _reject) => {9 let _ = setTimeout(() => {10 let q = query->String.toLowerCase11 resolve(fruits->Array.filter(fruit => fruit->String.toLowerCase->String.includes(q)))12 }, 400)13 })1415@xote.component16let make = () => {17 let text = Signal.make("")18 let query = Signal.make("")1920 // Search only after a 300ms pause in typing.21 Effect.run(() => {22 let next = Signal.get(text)23 let id = setTimeout(() => Signal.set(query, next), 300)24 Some(() => clearTimeout(id))25 })2627 let results = Resource.make(() => searchFruits(Signal.get(query)))2829 let onInput = (event: Dom.event) => {30 let target: {"value": string} = (event->Obj.magic)["target"]31 Signal.set(text, target["value"])32 }3334 <div class="fetch-demo">35 <input36 type_="search"37 class="fetch-demo-input"38 placeholder="Search fruit"39 value={Signal.get(text)}40 onInput41 />42 {switch Signal.get(results) {43 | Pending => <p class="fetch-demo-status"> {"Searching..."} </p>44 | Failed(_) => <p class="fetch-demo-status"> {"Search failed. Try again."} </p>45 | Ready([]) => <p class="fetch-demo-status"> {"No fruit matches."} </p>46 | Ready(items) | Refreshing(items) =>47 <ul class={Resource.isLoading(Signal.get(results)) ? "fetch-demo-list is-stale" : "fetch-demo-list"}>48 {items->Array.map(fruit => <li> {fruit} </li>)->View.fragment}49 </ul>50 }}51 </div>52}Searching...
The rest of this page takes that example apart.
Load data when a component mounts
Create the resource inside the component. It starts fetching straight away, and it belongs to the component: if the component goes away, a fetch still in flight is dropped.
1module Profile = {2 @xote.component3 let make = (~id: string) => {4 let user = Resource.make(() => loadUser(id))56 <section>7 {switch Signal.get(user) {8 | Pending => <p> {"Loading..."} </p>9 | Failed(_) => <p> {"Could not load this profile."} </p>10 | Ready(user) | Refreshing(user) =>11 <div>12 <h2> {user.name} </h2>13 <p> {user.email} </p>14 </div>15 }}16 </section>17 }18}
loadUser is any function that returns a promise, such as a wrapper around fetch. The switch covers every state, so the compiler tells you if you forget the error case.
Treat Ready and Refreshing the same when you only want to show data. Split them when you want to show that a reload is running, as the demo does by dimming the list.
Fetch again when a value changes
A resource tracks the signals its fetch reads before the first await. Change one of them and it fetches again. Here, changing the page loads that page:
1module TodoPages = {2 @xote.component3 let make = () => {4 let page = Signal.make(1)5 let todos = Resource.make(() => loadTodos(~page=Signal.get(page)))67 <div>8 {switch Signal.get(todos) {9 | Pending => <p> {"Loading..."} </p>10 | Failed(_) => <p> {"Could not load todos."} </p>11 | Ready(items) | Refreshing(items) =>12 <ul> {items->Array.map(todo => <li> {todo.title} </li>)->View.fragment} </ul>13 }}14 <button onClick={_ => Signal.update(page, n => n - 1)} disabled={Signal.get(page) == 1}>15 {"Previous"}16 </button>17 <span> {"Page "} {Signal.get(page)} </span>18 <button onClick={_ => Signal.update(page, n => n + 1)}> {"Next"} </button>19 </div>20 }21}
In an async fetch, read your signals at the top:
1let todos = Resource.make(async () => {2 let page = Signal.get(page) // tracked: read before the first await3 await waitForAuth()4 await loadTodos(~page)5})
Search as you type
Fetching on every keystroke wastes requests. Keep two signals: text follows the input, and query follows text after a pause. An effect does the waiting, and its cleanup cancels the timer whenever the user types again:
1let text = Signal.make("")2let query = Signal.make("")34Effect.run(() => {5 let next = Signal.get(text)6 let id = setTimeout(() => Signal.set(query, next), 300)7 Some(() => clearTimeout(id))8})910let results = Resource.make(() => searchFruits(Signal.get(query)))
The resource reads only query, so it fetches once per pause, not once per key.
Ignore stale responses
You don't have to do anything here. Only the latest fetch can settle a resource. If an older request answers after a newer one, its result is thrown away, so the screen never jumps back to old results.
Earlier requests are not aborted, though. They finish in the background and are ignored. Debouncing, as above, keeps that number small.
Reload, and update after saving
Resource.refetch fetches again with the same inputs. While it runs, the state is Refreshing with the old value, so the page doesn't flash back to a spinner:
1let todos = Resource.make(() => loadTodos(~page=1))23module Reload = {4 @xote.component5 let make = () =>6 <button onClick={_ => Resource.refetch(todos)} disabled={Resource.isLoading(Signal.get(todos))}>7 {"Reload"}8 </button>9}
To make a change feel instant, update the value yourself with Resource.mutate, save, then refetch to get what the server actually stored:
1let addTodo = async (todo: todo) => {2 // Show the new todo straight away...3 switch Signal.peek(todos)->Resource.value {4 | Some(list) => Resource.mutate(todos, [...list, todo])5 | None => ()6 }7 // ...then save it and load the list the server has.8 await saveTodo(todo)9 Resource.refetch(todos)10}
mutate also drops any fetch in flight, so a slow earlier load can't overwrite your update.
Wait for several requests at once
When a screen needs a few resources before it makes sense, wrap it in View.Suspense. The fallback shows until every resource created inside has loaded once:
1<View.Suspense fallback={<p> {"Loading your dashboard..."} </p>}>2 <Profile id />3 <TodoPages />4</View.Suspense>
Later reloads show as Refreshing inside each component and never bring the fallback back.
Data in server-rendered pages
Resources don't fetch during a server render. The HTML shows the Pending state, and the browser fetches after hydration. That's fine for most data.
When the data must be in the HTML, for search engines or a faster first paint, load it on the server before rendering and hand it to the client with SSRState:
1// Posts.res: shared by the server and the client2let posts: Signal.t<array<string>> = Signal.make([])3let codec = SSRState.Codec.array(SSRState.Codec.string)45// Server: load first, then record the value and render.6Signal.set(posts, await loadPosts())7SSRState.sync("posts", posts, codec)8let html = SSR.renderDocument(~stateScript=SSRState.generateScript(), app)910// Client: restore the value before hydrating.11SSRState.sync("posts", posts, codec)
Call sync after loading on the server: it records the signal's value at that moment.
Common mistakes
- Reading a signal after
await. It isn't tracked, so changing it won't fetch again. Read inputs first. - Creating a resource for every keystroke. Create it once and let a signal drive it.
- Forgetting the
Failedstate. Networks fail. Show a message, or throw the error to an error boundary. - Expecting data in server HTML. Resources only fetch in the browser; use
SSRStatewhen the server must render the data.
Summary
Load remote data with Resource.make: it runs an async function inside an effect, exposes the outcome as a signal of Resource.state<'a> (Pending | Ready('a) | Refreshing('a) | Failed(exn)), refetches when a signal read before the first await changes, and lets only the latest fetch settle. Use an Effect only for fire-and-forget work or when you need full manual control. The one rule that matters most: read every input signal before the first await of the fetch, or changes to it will not refetch.
Availability
| Item | Import / entry | First stable | Changed in 7.2.0 | Needs the PPX |
|---|---|---|---|---|
Resource (make, refetch, mutate, value, isLoading) | xote, xote/resource | 7.2.0 (new) | — | No |
View.Suspense | xote | 7.2.0 (new) | — | No |
View.ErrorBoundary | xote | 7.2.0 (new) | — | No |
Effect.run with cleanup (manual fetching before 7.2.0) | xote, xote/effect | stable (all 7.x) | — | No |
SSRState (sync, signal, generateScript, clear, Codec) | xote, xote/ssr-state | 7.0.0 | — | No |
Before 7.2.0, implement fetching with Effect.run plus a status signal and a stale flag (pattern below); Resource is not available.
Rules
Resource.make(fetch)starts the first fetch immediately (in an effect). The returned value is aSignal.t<Resource.state<'a>>; read it withSignal.get(tracked) orSignal.peek.- The fetch's dependencies are the signals it reads (tracked) synchronously, i.e. before its first
await. A change to any of them starts a new fetch. Reads after anawaitare not tracked. - Only the latest fetch can settle the state. A response from an earlier fetch that arrives late is discarded. Earlier requests are not aborted; they run to completion in the background (there is no
AbortSignalintegration). - State transitions: first fetch →
Pending; success →Ready(v); a later fetch while a value exists →Refreshing(previous); a fetch that throws or rejects →Failed(exn); a fetch afterFailed→Pending. Resource.refetch(r)fetches again with the same dependencies (stateRefreshing(v), orPendingafter a failure). It does nothing for a resource created during a server render.Resource.mutate(r, v)setsReady(v)immediately and drops any fetch in flight. The next dependency change orrefetchfetches again.- A resource created in a component body is owned by that component: removing the component disposes the resource and ignores its in-flight fetch. A resource created at module level has no owner and lives for the lifetime of the page (or server process).
- A resource created under a
View.Suspensemakes that suspense show itsfallbackuntil the resource's first fetch settles. Later refetches (Refreshing) never bring the fallback back. - During a server render (
SSR.renderToString/renderDocument) a resource created by the render does not fetch and staysPending. A resource created outside a render (module level) in a server process does fetch, and its state is shared by every request that process serves. - To send a failure to the nearest
View.ErrorBoundary, throw it where the state is read in a reactive leaf:| Failed(exn) => throw(exn). - Debouncing is not built in. Use an effect that copies an input signal into a query signal after a timer, with the timer cleared in the effect's cleanup; the resource reads only the query signal.
SSRState.sync/register/signalrecord the signal's encoded value at the moment they are called. Callsyncafter the data is loaded on the server; calling it again for the same id overwrites the recorded value.
Effect or resource?
| Need | Use |
|---|---|
| Show data with loading/error states | Resource.make |
| Refetch when inputs change, ignore stale responses | Resource.make (built in) |
| Wait for several loads before showing a region | Resource under View.Suspense |
| Optimistic update after a write | Resource.mutate then Resource.refetch |
| Fire-and-forget request (analytics, autosave) whose result is not shown | Effect.run |
| Polling, websockets, subscriptions | Effect.run with cleanup |
Before 7.2.0 (no Resource) | Effect.run + status signal + stale flag |
API
| Name | Signature | Behaviour |
|---|---|---|
Resource.state<'a> | Pending | Ready('a) | Refreshing('a) | Failed(exn) | Where the resource stands. |
Resource.t<'a> | Signal.t<state<'a>> | A resource is a signal. |
Resource.make | (unit => promise<'a>) => t<'a> | Creates and starts fetching; owned by the current component, if any. |
Resource.refetch | t<'a> => unit | Fetches again with the same dependencies. |
Resource.mutate | (t<'a>, 'a) => unit | Sets Ready(value), drops in-flight fetch. |
Resource.value | state<'a> => option<'a> | Some for Ready/Refreshing. |
Resource.isLoading | state<'a> => bool | true for Pending/Refreshing. |
View.Suspense | props fallback?: View.node, children?: View.node | Fallback until resources created below settle once. |
View.ErrorBoundary | props fallback: (exn, unit => unit) => View.node, onError?: exn => unit, children | Catches render/leaf/effect errors below; second fallback argument is reset. |
SSRState.sync | (string, Signal.t<'a>, Codec.t<'a>) => unit | Server: records current value. Client: restores it. |
SSRState.signal | (string, 'a, Codec.t<'a>) => Signal.t<'a> | Signal.make + sync at creation time. |
SSRState.generateScript | (~nonce: string=?) => string | <script> with all recorded values. |
SSRState.clear | unit => unit | Empties the server registry; call once per request. |
Patterns
Load in a component — Use when: a view shows remote data with all states handled.
1module Profile = {2 @xote.component3 let make = (~id: string) => {4 let user = Resource.make(() => loadUser(id))5 <section>6 {switch Signal.get(user) {7 | Pending => <p> {"Loading…"} </p>8 | Failed(_) => <p> {"Could not load this profile."} </p>9 | Ready(user) | Refreshing(user) =>10 <div>11 <h2> {user.name} </h2>12 <p> {user.email} </p>13 </div>14 }}15 </section>16 }17}
loadUser: string => promise<user> is any function returning a promise (e.g. a fetch wrapper). The exhaustive switch makes the compiler enforce the Failed branch.
Refetch on input change — Use when: pagination, filters, route params. Read inputs first in an async fetch:
1let page = Signal.make(1)23let todos = Resource.make(async () => {4 let page = Signal.get(page) // tracked: before the first await5 await waitForAuth()6 await loadTodos(~page)7})
Debounced search — Use when: a query comes from typing.
1@xote.component2let make = () => {3 let text = Signal.make("")4 let query = Signal.make("")56 Effect.run(() => {7 let next = Signal.get(text)8 let id = setTimeout(() => Signal.set(query, next), 300)9 Some(() => clearTimeout(id))10 })1112 let results = Resource.make(() => searchFruits(Signal.get(query)))1314 <p> {Resource.isLoading(Signal.get(results)) ? "Searching…" : "Done"} </p>15}
The effect and the resource are created in the component body, so both are disposed with the component.
Optimistic update, then reconcile — Use when: the user adds or edits an item.
1let addTodo = async (todo: todo) => {2 switch Signal.peek(todos)->Resource.value {3 | Some(list) => Resource.mutate(todos, [...list, todo])4 | None => ()5 }6 await saveTodo(todo)7 Resource.refetch(todos)8}
Parallel requests — Use when: one view needs several results. Either combine in one resource (one state for all):
1let both = Resource.make(() => Promise.all2((loadUser("ada"), loadTodos(~page=1))))
or create one resource per component and wrap the region in View.Suspense, which waits for every resource created inside it:
1<View.Suspense fallback={<p> {"Loading your dashboard…"} </p>}>2 <Profile id="ada" />3 <TodoPages />4</View.Suspense>
Route failures to an error boundary — Use when: a failure should replace a whole region with a retryable panel.
1module UserName = {2 @xote.component3 let make = (~id: string) => {4 let user = Resource.make(() => loadUser(id))5 <p>6 {switch Signal.get(user) {7 | Failed(error) => throw(error)8 | Pending => ""9 | Ready(user) | Refreshing(user) => user.name10 }}11 </p>12 }13}
Wrap the caller in <View.ErrorBoundary fallback={(_error, reset) => …}>; reset re-creates the subtree, which creates a new resource and fetches again.
Manual fetching before 7.2.0 — Use when: Resource is unavailable.
1type status = Loading | Ready | Failed23@xote.component4let make = () => {5 let id = Signal.make("ada")6 let status = Signal.make(Loading)7 let name = Signal.make("")89 Effect.run(() => {10 let current = Signal.get(id)11 let stale = ref(false)12 Signal.set(status, Loading)13 loadUser(current)14 ->Promise.thenResolve(user =>15 if !stale.contents {16 Signal.batch(() => {17 Signal.set(name, user.name)18 Signal.set(status, Ready)19 })20 }21 )22 ->Promise.catch(_ => {23 if !stale.contents {24 Signal.set(status, Failed)25 }26 Promise.resolve()27 })28 ->ignore29 Some(() => stale := true)30 })3132 <p>33 {switch Signal.get(status) {34 | Loading => "Loading…"35 | Failed => "Could not load."36 | Ready => Signal.get(name)37 }}38 </p>39}
Data in server-rendered HTML — Use when: crawlers or first paint need the data.
1// Shared module2let posts: Signal.t<array<string>> = Signal.make([])3let codec = SSRState.Codec.array(SSRState.Codec.string)45// Server, per request6let renderPage = async (app: unit => View.node) => {7 SSRState.clear()8 Signal.set(posts, await loadPosts())9 SSRState.sync("posts", posts, codec) // after the value is final10 SSR.renderDocument(~stateScript=SSRState.generateScript(), app)11}1213// Client entry, before hydrating14SSRState.sync("posts", posts, codec)
Anti-patterns
-
Reading an input after
await. Wrong:Resource.make(async () => { await waitForAuth(); await loadTodos(~page=Signal.get(page)) }). Symptom: changingpagedoes nothing; the list never refetches. Right:let page = Signal.get(page)as the first statement, then the awaits. Why: dependency tracking stops at the firstawait. -
Creating a resource per keystroke or per event. Wrong:
onInput={e => results := Resource.make(() => search(value(e)))}. Symptom: leaked resources, no stale-response protection between them, state not wired to the view. Right: one resource that reads aquerysignal; the handler only sets the signal. -
SSRState.signalfor data loaded later. Wrong:let posts = SSRState.signal("posts", [], codec)at module level, thenSignal.set(posts, await loadPosts())on the server. Symptom: the HTML contains the posts, butwindow.__XOTE_STATE__has"posts":[]; after hydration the client resets the list to empty. Right:Signal.make([]), load, thenSSRState.sync("posts", posts, codec)(or callsyncagain after loading). Why: the value is encoded whensignal/syncruns, not whengenerateScriptruns. -
Module-level resource on the server. Wrong:
let todos = Resource.make(() => loadTodos(~page=1))in a module imported by the server entry. Symptom: the server fetches at import time and every request shares one state; data can leak between users. Right: create resources inside components (they do not fetch during server rendering), or load per request and transfer withSSRState. -
Ignoring
Failed. Wrong:| _ => ""swallowing every state other thanReady. Symptom: a network error looks like an empty page forever. Right: an explicitFailed(_)branch, orthrowto an error boundary.
Edge cases
- A non-
asyncfetch such as() => search(Signal.get(query))evaluatesSignal.get(query)synchronously while building the promise, soqueryis tracked. - Setting a dependency to an equal value (strict equality) does not notify and does not refetch.
Refreshing(v)keeps the previous value: renderReady(v) | Refreshing(v)together to avoid a loading flash, and useResource.isLoadingfor a subtle indicator.- A rejected promise's payload arrives as
Failed(exn), with JavaScript errors wrapped as a ReScript exception. Model expected failures (404, validation) as values in the resolved data (for example aresult) rather than matching on error messages. View.Suspenseonly waits for resources created below it (by component bodies inside it), wherever they are read.- Debounce with
setTimeoutinside an effect requires the cleanup to callclearTimeout; without it, every keystroke eventually fires. - In tests, a resource settles after the promise microtasks run: await a
setTimeout(_, 0)tick before asserting (see the Testing guide).
SSR and hydration
- Resources created during a server render stay
Pendingand render their pending branch (or the nearestSuspensefallback). After hydration the browser fetches. - For data that must be in the HTML: load on the server,
SSRState.syncafter loading, emitSSRState.generateScript()(e.g.~stateScriptofSSR.renderDocument), and callSSRState.syncwith the same id and codec on the client before hydrating.SSRState.restorekeeps the signal's current value when the id is missing or fails to decode. - Call
SSRState.clear()at the start of each request in a long-lived server process; otherwise a previous request's values appear in the next response.
Verify
- Compile: an incomplete
switch Signal.get(resource)gives "this pattern-matching is not exhaustive" listing the missing constructor; add it. - Test (async Zekr suite, run from its own entry with
runAsyncSuites):
1let settle = () => Promise.make((resolve, _) => setTimeout(() => resolve(), 0)->ignore)23asyncTest("a later dependency change wins", async () => {4 let id = Signal.make(1)5 let resolvers: array<string => unit> = []6 let user = Resource.make(() => {7 let n = Signal.get(id)8 Promise.make((resolve, _) => resolvers->Array.push(v => resolve(v ++ Int.toString(n)))->ignore)9 })10 Signal.set(id, 2)11 (resolvers->Array.getUnsafe(1))("user")12 await settle()13 (resolvers->Array.getUnsafe(0))("user") // the stale response arrives last14 await settle()15 assertEqual(Signal.peek(user), Resource.Ready("user2"))16}),
- Server state: in a Node script, call your server render and check the returned HTML contains
window.__XOTE_STATE__={"posts":[…]}with the loaded values, not the initial ones.
Related
/docs/learn/async-data—ResourceandView.Suspensereference./docs/learn/lifecycle—View.ErrorBoundary./docs/learn/effects— cleanups, ownership, manual fetching./docs/advanced/ssr—SSRState, rendering and hydration./docs/guides/testing— async test setup.