Skip to content

Fetching dataNew in 7.2

Load data, show loading and error states, refetch when inputs change, and search as people type.

docs/guides/fetching-data.md
Raw Markdown

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.

FruitSearch.res
1let fruits = [
2 "Apple", "Apricot", "Banana", "Blackberry", "Blueberry", "Cherry", "Grape", "Lemon",
3 "Lime", "Mango", "Orange", "Peach", "Pear", "Plum", "Raspberry", "Strawberry",
4]
5
6// 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.toLowerCase
11 resolve(fruits->Array.filter(fruit => fruit->String.toLowerCase->String.includes(q)))
12 }, 400)
13 })
14
15@xote.component
16let make = () => {
17 let text = Signal.make("")
18 let query = Signal.make("")
19
20 // 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 })
26
27 let results = Resource.make(() => searchFruits(Signal.get(query)))
28
29 let onInput = (event: Dom.event) => {
30 let target: {"value": string} = (event->Obj.magic)["target"]
31 Signal.set(text, target["value"])
32 }
33
34 <div class="fetch-demo">
35 <input
36 type_="search"
37 class="fetch-demo-input"
38 placeholder="Search fruit"
39 value={Signal.get(text)}
40 onInput
41 />
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...

A debounced search over a pretend server.

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.component
3 let make = (~id: string) => {
4 let user = Resource.make(() => loadUser(id))
5
6 <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.component
3 let make = () => {
4 let page = Signal.make(1)
5 let todos = Resource.make(() => loadTodos(~page=Signal.get(page)))
6
7 <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 await
3 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("")
3
4Effect.run(() => {
5 let next = Signal.get(text)
6 let id = setTimeout(() => Signal.set(query, next), 300)
7 Some(() => clearTimeout(id))
8})
9
10let 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))
2
3module Reload = {
4 @xote.component
5 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 client
2let posts: Signal.t<array<string>> = Signal.make([])
3let codec = SSRState.Codec.array(SSRState.Codec.string)
4
5// 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)
9
10// 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 Failed state. 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 SSRState when 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

ItemImport / entryFirst stableChanged in 7.2.0Needs the PPX
Resource (make, refetch, mutate, value, isLoading)xote, xote/resource7.2.0 (new)—No
View.Suspensexote7.2.0 (new)—No
View.ErrorBoundaryxote7.2.0 (new)—No
Effect.run with cleanup (manual fetching before 7.2.0)xote, xote/effectstable (all 7.x)—No
SSRState (sync, signal, generateScript, clear, Codec)xote, xote/ssr-state7.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

  1. Resource.make(fetch) starts the first fetch immediately (in an effect). The returned value is a Signal.t<Resource.state<'a>>; read it with Signal.get (tracked) or Signal.peek.
  2. 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 an await are not tracked.
  3. 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 AbortSignal integration).
  4. 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 after Failed → Pending.
  5. Resource.refetch(r) fetches again with the same dependencies (state Refreshing(v), or Pending after a failure). It does nothing for a resource created during a server render.
  6. Resource.mutate(r, v) sets Ready(v) immediately and drops any fetch in flight. The next dependency change or refetch fetches again.
  7. 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).
  8. A resource created under a View.Suspense makes that suspense show its fallback until the resource's first fetch settles. Later refetches (Refreshing) never bring the fallback back.
  9. During a server render (SSR.renderToString/renderDocument) a resource created by the render does not fetch and stays Pending. 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.
  10. To send a failure to the nearest View.ErrorBoundary, throw it where the state is read in a reactive leaf: | Failed(exn) => throw(exn).
  11. 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.
  12. SSRState.sync/register/signal record the signal's encoded value at the moment they are called. Call sync after the data is loaded on the server; calling it again for the same id overwrites the recorded value.

Effect or resource?

NeedUse
Show data with loading/error statesResource.make
Refetch when inputs change, ignore stale responsesResource.make (built in)
Wait for several loads before showing a regionResource under View.Suspense
Optimistic update after a writeResource.mutate then Resource.refetch
Fire-and-forget request (analytics, autosave) whose result is not shownEffect.run
Polling, websockets, subscriptionsEffect.run with cleanup
Before 7.2.0 (no Resource)Effect.run + status signal + stale flag

API

NameSignatureBehaviour
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.refetcht<'a> => unitFetches again with the same dependencies.
Resource.mutate(t<'a>, 'a) => unitSets Ready(value), drops in-flight fetch.
Resource.valuestate<'a> => option<'a>Some for Ready/Refreshing.
Resource.isLoadingstate<'a> => booltrue for Pending/Refreshing.
View.Suspenseprops fallback?: View.node, children?: View.nodeFallback until resources created below settle once.
View.ErrorBoundaryprops fallback: (exn, unit => unit) => View.node, onError?: exn => unit, childrenCatches render/leaf/effect errors below; second fallback argument is reset.
SSRState.sync(string, Signal.t<'a>, Codec.t<'a>) => unitServer: 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.clearunit => unitEmpties 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.component
3 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)
2
3let todos = Resource.make(async () => {
4 let page = Signal.get(page) // tracked: before the first await
5 await waitForAuth()
6 await loadTodos(~page)
7})

Debounced search — Use when: a query comes from typing.

1@xote.component
2let make = () => {
3 let text = Signal.make("")
4 let query = Signal.make("")
5
6 Effect.run(() => {
7 let next = Signal.get(text)
8 let id = setTimeout(() => Signal.set(query, next), 300)
9 Some(() => clearTimeout(id))
10 })
11
12 let results = Resource.make(() => searchFruits(Signal.get(query)))
13
14 <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.component
3 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.name
10 }}
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 | Failed
2
3@xote.component
4let make = () => {
5 let id = Signal.make("ada")
6 let status = Signal.make(Loading)
7 let name = Signal.make("")
8
9 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 ->ignore
29 Some(() => stale := true)
30 })
31
32 <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 module
2let posts: Signal.t<array<string>> = Signal.make([])
3let codec = SSRState.Codec.array(SSRState.Codec.string)
4
5// Server, per request
6let 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 final
10 SSR.renderDocument(~stateScript=SSRState.generateScript(), app)
11}
12
13// Client entry, before hydrating
14SSRState.sync("posts", posts, codec)

Anti-patterns

  1. Reading an input after await. Wrong: Resource.make(async () => { await waitForAuth(); await loadTodos(~page=Signal.get(page)) }). Symptom: changing page does nothing; the list never refetches. Right: let page = Signal.get(page) as the first statement, then the awaits. Why: dependency tracking stops at the first await.

  2. 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 a query signal; the handler only sets the signal.

  3. SSRState.signal for data loaded later. Wrong: let posts = SSRState.signal("posts", [], codec) at module level, then Signal.set(posts, await loadPosts()) on the server. Symptom: the HTML contains the posts, but window.__XOTE_STATE__ has "posts":[]; after hydration the client resets the list to empty. Right: Signal.make([]), load, then SSRState.sync("posts", posts, codec) (or call sync again after loading). Why: the value is encoded when signal/sync runs, not when generateScript runs.

  4. 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 with SSRState.

  5. Ignoring Failed. Wrong: | _ => "" swallowing every state other than Ready. Symptom: a network error looks like an empty page forever. Right: an explicit Failed(_) branch, or throw to an error boundary.

Edge cases

  • A non-async fetch such as () => search(Signal.get(query)) evaluates Signal.get(query) synchronously while building the promise, so query is tracked.
  • Setting a dependency to an equal value (strict equality) does not notify and does not refetch.
  • Refreshing(v) keeps the previous value: render Ready(v) | Refreshing(v) together to avoid a loading flash, and use Resource.isLoading for 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 a result) rather than matching on error messages.
  • View.Suspense only waits for resources created below it (by component bodies inside it), wherever they are read.
  • Debounce with setTimeout inside an effect requires the cleanup to call clearTimeout; 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 Pending and render their pending branch (or the nearest Suspense fallback). After hydration the browser fetches.
  • For data that must be in the HTML: load on the server, SSRState.sync after loading, emit SSRState.generateScript() (e.g. ~stateScript of SSR.renderDocument), and call SSRState.sync with the same id and codec on the client before hydrating. SSRState.restore keeps 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)
2
3asyncTest("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 last
14 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.
  • /docs/learn/async-data — Resource and View.Suspense reference.
  • /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.