Skip to content

Tutorial: temperature converter

Build a small temperature converter step by step, and meet signals, computeds and effects along the way.

docs/tutorial.md
Raw Markdown

In this tutorial you'll build a small temperature converter, one step at a time. Along the way you'll use the three ideas everything in Xote is built on: a signal holds a value, a computed derives a new value from it, and an effect does work outside the page when a value changes.

It assumes you have a project set up. If you don't, follow the Quick start first; it takes a few minutes.

Step 1: Show a temperature

Start with a component that displays one temperature. It takes the value and a unit as props and renders them as text. There's nothing reactive yet: it's a plain function that returns some markup.

1// TemperatureDisplay.res
2type tempUnit = Celsius | Fahrenheit | Kelvin
3
4let symbolFor = unit =>
5 switch unit {
6 | Celsius => "°C"
7 | Fahrenheit => "°F"
8 | Kelvin => "K"
9 }
10
11let labelFor = unit =>
12 switch unit {
13 | Celsius => "Celsius"
14 | Fahrenheit => "Fahrenheit"
15 | Kelvin => "Kelvin"
16 }
17
18@xote.component
19let make = (~value: float, ~unit: tempUnit) =>
20 <div class="temp-display">
21 <span class="temp-value"> {value->Float.toFixed(~digits=1)} </span>
22 <span class="temp-unit"> {symbolFor(unit)} </span>
23 <span class="temp-label"> {labelFor(unit)} </span>
24 </div>

Render it from your entry file:

1// App.res
2View.mountById(<TemperatureDisplay value=22.0 unit=Celsius />, "app")
TemperatureDisplay.res
1@xote.component
2let make = (~value: float, ~unit: tempUnit) =>
3 <div class="temp-display">
4 <span class="temp-value"> {value->Float.toFixed(~digits=1)} </span>
5 <span class="temp-unit"> {symbolFor(unit)} </span>
6 <span class="temp-label"> {labelFor(unit)} </span>
7 </div>
22.0°CCelsius
A static display: 22 °C.

Takeaway: a component is a function you call once. It builds its markup and returns it. Read more in Components.

Step 2: Make it react to a slider

Now let the reader change the temperature. Put the value in a signal, a container that remembers who reads it and tells them when it changes. A range input writes to the signal, and the display reads from it.

The display changes in two small ways: its value prop becomes a Signal.t<float>, and it reads that signal with Signal.get.

1// TemperatureDisplay.res (changed lines)
2@xote.component
3let make = (~value: Signal.t<float>, ~unit: tempUnit) =>
4 <div class="temp-display">
5 <span class="temp-value"> {Signal.get(value)->Float.toFixed(~digits=1)} </span>
6 // …the unit and label spans stay the same
7 </div>

Then a converter component owns the signal and the slider:

Converter.res
1let celsius = Signal.make(22.0)
2
3@get external target: Dom.event => {"value": string} = "target"
4
5let onSlide = evt =>
6 switch Float.fromString(target(evt)["value"]) {
7 | Some(value) => Signal.set(celsius, value)
8 | None => ()
9 }
10
11@xote.component
12let make = () =>
13 <div>
14 <TemperatureDisplay value=celsius unit=Celsius />
15 <input
16 type_="range"
17 min="-20"
18 max="40"
19 step="0.5"
20 value={Signal.get(celsius)->Float.toString}
21 onInput=onSlide
22 />
23 </div>
22.0°CCelsius
Drag the slider: the number follows.

A few things to notice:

  • The @get external line is a one-line binding that reads event.target, so the handler can get the slider's value as a string.
  • Signal.set writes a new value. Everything that read celsius with Signal.get updates.
  • The display receives the signal itself, value=celsius, not its current value. A component's props are read once when it's created, so the signal is what lets the display keep up.

Takeaway: state lives in signals; reading one with Signal.get inside your markup keeps that spot up to date. Read more in Signals.

Step 3: Derive Fahrenheit and Kelvin

Fahrenheit and Kelvin aren't new state; they're always worked out from Celsius. That's a computed: a value defined by a function of other signals. It recalculates by itself when those signals change, and you never set it directly.

Converter.res
1let celsius = Signal.make(22.0)
2let fahrenheit = Computed.make(() => Signal.get(celsius) *. 9.0 /. 5.0 +. 32.0)
3let kelvin = Computed.make(() => Signal.get(celsius) +. 273.15)
4
5@xote.component
6let make = () =>
7 <div>
8 <TemperatureDisplay value=celsius unit=Celsius />
9 <TemperatureDisplay value=fahrenheit unit=Fahrenheit />
10 <TemperatureDisplay value=kelvin unit=Kelvin />
11 <input
12 type_="range"
13 min="-20"
14 max="40"
15 step="0.5"
16 value={Signal.get(celsius)->Float.toString}
17 onInput=onSlide
18 />
19 </div>
22.0°CCelsius
71.6°FFahrenheit
295.1KKelvin
One signal drives three readouts. The panel lists every text change the page makes.

A computed is a signal, so TemperatureDisplay accepts fahrenheit and kelvin without any changes.

Drag the slider and watch the panel next to the demo. It records every change the page makes to its text. Each move changes exactly three text nodes, the three numbers, and nothing else: no components run again and no markup is rebuilt. That's the core idea behind Xote; Thinking in signals explains it in more depth.

Takeaway: if a value can be worked out from other values, make it a computed instead of a second signal you have to keep in sync. Read more in Computeds.

Step 4: Fetch the weather with an effect

Finally, show the real temperature in a world capital. Talking to the network is work outside the page, which is what an effect is for: a function that runs once, then runs again whenever a signal it read changes.

First, a few helpers: a list of capitals, ways to pick one, and a function that asks the free Open-Meteo API for the current temperature. The two type declarations describe the part of the JSON response we use.

1// Weather.res
2type capital = {name: string, lat: float, lng: float}
3
4let capitals = [
5 {name: "Paris", lat: 48.8566, lng: 2.3522},
6 {name: "Tokyo", lat: 35.6762, lng: 139.6503},
7 {name: "Nairobi", lat: -1.2921, lng: 36.8219},
8]
9
10let pickCapital = () => capitals->Array.getUnsafe(Math.Int.random(0, Array.length(capitals)))
11
12let otherCapital = (current: capital) => {
13 let others = capitals->Array.filter(capital => capital.name != current.name)
14 others->Array.getUnsafe(Math.Int.random(0, Array.length(others)))
15}
16
17type response
18type currentWeather = {temperature: float}
19type forecast = {current_weather: currentWeather}
20
21@val external fetch: string => promise<response> = "fetch"
22@send external json: response => promise<forecast> = "json"
23
24let fetchTemperature = async (capital: capital) => {
25 let url =
26 "https://api.open-meteo.com/v1/forecast" ++
27 `?latitude=${capital.lat->Float.toString}` ++
28 `&longitude=${capital.lng->Float.toString}` ++ "&current_weather=true"
29 let response = await fetch(url)
30 let forecast = await json(response)
31 forecast.current_weather.temperature
32}

The card keeps the selected capital in a signal. Its effect reads that signal, so picking another capital runs the effect again and fetches new data. The computeds from step 3 are unchanged; only where celsius gets its value from is new.

WeatherCard.res
1open Weather
2
3type status = Loading | Ready | Failed
4
5let rowClass = status =>
6 switch status {
7 | Loading => "temp-row is-loading"
8 | Failed => "temp-row is-failed"
9 | Ready => "temp-row"
10 }
11
12let statusText = status =>
13 switch status {
14 | Loading => "Fetching the current weather…"
15 | Failed => "Couldn't reach the weather service."
16 | Ready => "Live from Open-Meteo."
17 }
18
19@xote.component
20let make = () => {
21 let capital = Signal.make(pickCapital())
22 let status = Signal.make(Loading)
23 let celsius = Signal.make(0.0)
24 let fahrenheit = Computed.make(() => Signal.get(celsius) *. 9.0 /. 5.0 +. 32.0)
25 let kelvin = Computed.make(() => Signal.get(celsius) +. 273.15)
26
27 Effect.run(() => {
28 let current = Signal.get(capital)
29 let stale = ref(false)
30 Signal.set(status, Loading)
31
32 fetchTemperature(current)
33 ->Promise.thenResolve(temperature =>
34 if !stale.contents {
35 Signal.set(celsius, temperature)
36 Signal.set(status, Ready)
37 }
38 )
39 ->Promise.catch(_ => {
40 if !stale.contents {
41 Signal.set(status, Failed)
42 }
43 Promise.resolve()
44 })
45 ->ignore
46
47 Some(() => stale := true)
48 })
49
50 let shuffle = _ => Signal.update(capital, otherCapital)
51
52 <div>
53 <h3> {"Now in "} {Signal.get(capital).name} </h3>
54 <div class={rowClass(Signal.get(status))}>
55 <TemperatureDisplay value=celsius unit=Celsius />
56 <TemperatureDisplay value=fahrenheit unit=Fahrenheit />
57 <TemperatureDisplay value=kelvin unit=Kelvin />
58 </div>
59 <p class="status"> {statusText(Signal.get(status))} </p>
60 <button onClick=shuffle> {"Try another capital"} </button>
61 </div>
62}
Now inParis
0.0°CCelsius
32.0°FFahrenheit
273.1KKelvin

Fetching the current weather…

Real weather from a world capital. Try another one.

Three details are worth a closer look:

  • The cleanup. The effect returns Some(() => stale := true). Xote runs that function before the effect runs again. If you switch capitals before a slow response arrives, the old request is marked stale and its result is ignored, so it can't overwrite the newer one.
  • No layout shift. The readouts never leave the page. While a request is in flight, rowClass adds is-loading, and the stylesheet swaps each number for a placeholder of the same size; the status line below always holds one line of text. Switching capitals, or a failed request, changes classes and text, never the layout. Only the class attribute and the status text depend on status, so those are the only things that update when it changes.
  • The signals live inside the component. Each card has its own state, and its effect stops when the card is removed from the page.

Takeaway: use effects for work outside the page, like requests, timers and storage, and return a cleanup whenever there's something to undo. Read more in Effects.

Bonus: let a resource do the work

New in 7.2

Step 4 tracks the loading state by hand: a status signal, a stale flag, and a switch over the outcome. Xote has built-ins for exactly this, and the card gets shorter with them:

  • A resource runs an async function and keeps its result in a signal: Pending, then Ready(value), Refreshing(value) while it fetches again, or Failed(error). Signals it reads before its first await are its inputs, so changing capital fetches again, and a late answer for an old capital is ignored for you.
  • View.Suspense shows a fallback until the resources created inside it have loaded once. Here the fallback is the same placeholder cards as before, so there's still no layout shift.
  • View.ErrorBoundary catches an error thrown while rendering and shows a fallback with a retry function. The readouts throw when the resource fails, and the boundary shows a panel the same size as the readouts.
WeatherCard.res
1open Weather
2
3module WeatherReadouts = {
4 @xote.component
5 let make = (~capital: Signal.t<capital>) => {
6 let weather = Resource.make(() => fetchTemperature(Signal.get(capital)))
7 let celsius = Computed.make(() => Signal.get(weather)->Resource.value->Option.getOr(0.0))
8 let fahrenheit = Computed.make(() => Signal.get(celsius) *. 9.0 /. 5.0 +. 32.0)
9 let kelvin = Computed.make(() => Signal.get(celsius) +. 273.15)
10
11 <div>
12 <div class={Resource.isLoading(Signal.get(weather)) ? "temp-row is-refreshing" : "temp-row"}>
13 <TemperatureDisplay value=celsius unit=Celsius />
14 <TemperatureDisplay value=fahrenheit unit=Fahrenheit />
15 <TemperatureDisplay value=kelvin unit=Kelvin />
16 </div>
17 <p class="status">
18 {switch Signal.get(weather) {
19 | Failed(error) => throw(error)
20 | Refreshing(_) | Pending => "Updating…"
21 | Ready(_) => "Live from Open-Meteo."
22 }}
23 </p>
24 </div>
25 }
26}
27
28@xote.component
29let make = () => {
30 let capital = Signal.make(pickCapital())
31 let shuffle = _ => Signal.update(capital, otherCapital)
32
33 <div>
34 <h3> {"Now in "} {Signal.get(capital).name} </h3>
35 <View.ErrorBoundary
36 fallback={(_error, retry) =>
37 <div class="error">
38 <LoadingReadouts />
39 <div class="error-message">
40 <p> {"Couldn't reach the weather service."} </p>
41 <button onClick={_ => retry()}> {"Try again"} </button>
42 </div>
43 </div>}>
44 <View.Suspense fallback={<LoadingReadouts />}>
45 <WeatherReadouts capital />
46 </View.Suspense>
47 </View.ErrorBoundary>
48 <button onClick=shuffle> {"Try another capital"} </button>
49 </div>
50}
Now inParis
0.0°CCelsius
0.0°FFahrenheit
0.0KKelvin

Fetching the current weather…

The same card on Resource, Suspense and ErrorBoundary.

What changed from step 4:

  • The resource replaces the effect, the status signal and the stale flag. Resource.make takes the fetch; Resource.value reads its result, with 0.0 until there is one.
  • The component that creates the resource sits inside the Suspense. That's what makes the Suspense wait for it. LoadingReadouts is the step 1 display three times, with the placeholder class on its row.
  • After the first load, the Suspense stays out of the way. Picking another capital moves the resource to Refreshing: the old numbers stay on screen, dimmed, until the new ones arrive.
  • A failure goes to the boundary. throw(error) in the status line hands the failure to the nearest View.ErrorBoundary. Its retry renders the readouts again, which creates a fresh resource and fetches again. The fallback lays its message over hidden placeholder cards, so it takes exactly the readouts' space at any width.

Takeaway: for data that loads, reach for a resource. Suspense and error boundaries keep the loading and failure states out of your component's logic. Read more in Async data and Refs and lifecycle, and see the Fetching data guide for more recipes.

Where to go next

You've used every core piece of Xote: components, signals, computeds and effects. From here:

  • Thinking in signals explains why only those three text nodes changed, and how to design components around it.
  • Rendering covers lists, conditionals, attributes and events.
  • Forms and inputs builds on the slider from step 2.
  • The Signal API lists everything a signal can do.

Summary

Reference implementation of the tutorial app: a temperature converter (one signal, two computeds, a slider) and a live weather card in two versions, one built on Effect.run with manual loading state, one built on Resource, View.Suspense and View.ErrorBoundary. Each part is annotated with the rule it relies on. Use this page as a template for "a component that derives values and loads remote data without layout shift". The human page teaches the same app step by step; this page gives the final code.

Availability

PartRequiresVersion
Converter (Signal, Computed, PPX)xote, ppx-flagsstable 7.1.0
Weather card with Effect.runxotestable 7.1.0
Weather card with Resource, View.Suspense, View.ErrorBoundaryxote7.2.0 (new)
Networkfetch (browser or Node 18+), Open-Meteo API (no key)

Rules

  1. TemperatureDisplay takes ~value: Signal.t<float>, not float: user-component props are read once, so a float prop would freeze (see /docs/thinking-in-signals, rule 13).
  2. fahrenheit and kelvin are computeds of celsius; they MUST NOT be separate signals kept in sync. A computed is itself a Signal.t, so it can be passed where a signal is expected.
  3. The slider's value reads celsius in attribute position, so it is a reactive leaf; onInput writes celsius. Only the three number texts and the slider's value update on input.
  4. In the effect version, the effect reads capital before starting the request, so capital is its only dependency; it writes status and celsius, which it does not read.
  5. The effect returns Some(() => stale := true). Xote runs it before the next run (capital changed) and when the owner is disposed, so a late response for an old capital is ignored.
  6. The effect is guarded by SSRContext.isClient because the docs site server-renders this page; a client-only app does not need the guard. In the resource version no guard is needed: a resource created during a server render does not fetch.
  7. No-layout-shift technique (both versions): the readout row is always rendered; loading and failure are expressed by CSS classes on the row (is-loading, is-failed, is-refreshing) and by the text of a status line that always occupies one line. Placeholders MUST have the same box size as the real content.
  8. In the resource version, the resource is created inside Readouts, which is rendered under View.Suspense: a resource suspends the nearest Suspense above the component that created it. Suspense shows its fallback until the first fetch settles, never again afterwards.
  9. On a refetch the resource state is Refreshing(previous): the previous numbers stay and are dimmed via Resource.isLoading.
  10. A failure is routed to the error boundary by throwing in a reactive leaf: | Failed(error) => throw(error). The boundary replaces its subtree with fallback; retry rebuilds the subtree, which creates a new resource and fetches again.
  11. The boundary's fallback renders the placeholder row underneath its message (stacked with CSS grid), so the fallback has exactly the readouts' size at any width.
  12. "Try another capital" uses Signal.update(capital, otherCapital), which never returns the current capital; setting an equal value would not notify and nothing would reload.

API

NameSignatureBehaviour
Computed.make(unit => 'a, ~name: string=?, ~equals: ('a, 'a) => bool=?) => Signal.t<'a>derived value
Effect.run(unit => option<unit => unit>, ~name: string=?) => unitruns now and on change; cleanup before next run
Resource.make(unit => promise<'a>) => Resource.t<'a>async value as a signal of Pending / Ready / Refreshing / Failed
Resource.valueResource.state<'a> => option<'a>value of Ready/Refreshing
Resource.isLoadingResource.state<'a> => booltrue for Pending and Refreshing
View.SuspenseJSX: <View.Suspense fallback> children </View.Suspense>fallback until resources below have settled once
View.ErrorBoundaryJSX: fallback: (exn, unit => unit) => View.node, onError?catches errors thrown while rendering/updating its subtree
SSRContext.isClientbooltrue in the browser

Patterns

Shared helpers

1// Units.res
2type tempUnit = Celsius | Fahrenheit | Kelvin
3
4let symbolFor = unit =>
5 switch unit {
6 | Celsius => "°C"
7 | Fahrenheit => "°F"
8 | Kelvin => "K"
9 }
10
11let labelFor = unit =>
12 switch unit {
13 | Celsius => "Celsius"
14 | Fahrenheit => "Fahrenheit"
15 | Kelvin => "Kelvin"
16 }
17
18let toFahrenheit = celsius => celsius *. 9.0 /. 5.0 +. 32.0
19let toKelvin = celsius => celsius +. 273.15
1// TemperatureDisplay.res — rule 1
2open Units
3
4@xote.component
5let make = (~value: Signal.t<float>, ~unit: tempUnit) =>
6 <div class="temp-display">
7 <span class="temp-value"> {Signal.get(value)->Float.toFixed(~digits=1)} </span>
8 <span class="temp-unit"> {symbolFor(unit)} </span>
9 <span class="temp-label"> {labelFor(unit)} </span>
10 </div>

Converter (rules 2–3)

1// Converter.res
2open Units
3
4@get external target: Dom.event => {"value": string} = "target"
5
6let celsius = Signal.make(22.0)
7let fahrenheit = Computed.make(() => Signal.get(celsius)->toFahrenheit)
8let kelvin = Computed.make(() => Signal.get(celsius)->toKelvin)
9
10let onSlide = (event: Dom.event) =>
11 switch Float.fromString(target(event)["value"]) {
12 | Some(value) => Signal.set(celsius, value)
13 | None => ()
14 }
15
16@xote.component
17let make = () =>
18 <div>
19 <div class="temp-row">
20 <TemperatureDisplay value=celsius unit=Celsius />
21 <TemperatureDisplay value=fahrenheit unit=Fahrenheit />
22 <TemperatureDisplay value=kelvin unit=Kelvin />
23 </div>
24 <input
25 type_="range"
26 min="-20"
27 max="40"
28 step="0.5"
29 value={Signal.get(celsius)->Float.toString}
30 onInput=onSlide
31 />
32 </div>

Weather data

1// Weather.res
2type capital = {name: string, lat: float, lng: float}
3
4let capitals = [
5 {name: "Paris", lat: 48.8566, lng: 2.3522},
6 {name: "Tokyo", lat: 35.6762, lng: 139.6503},
7 {name: "Nairobi", lat: -1.2921, lng: 36.8219},
8]
9
10// Rule 12: never returns `current`.
11let otherCapital = (current: capital) => {
12 let others = capitals->Array.filter(capital => capital.name != current.name)
13 others->Array.getUnsafe(Math.Int.random(0, Array.length(others)))
14}
15
16type response
17type currentWeather = {temperature: float}
18type forecast = {current_weather: currentWeather}
19
20@val external fetch: string => promise<response> = "fetch"
21@send external json: response => promise<forecast> = "json"
22
23let fetchTemperature = async (capital: capital) => {
24 let url =
25 "https://api.open-meteo.com/v1/forecast" ++
26 `?latitude=${capital.lat->Float.toString}` ++
27 `&longitude=${capital.lng->Float.toString}` ++ "&current_weather=true"
28 let response = await fetch(url)
29 let forecast = await json(response)
30 forecast.current_weather.temperature
31}

Weather card, effect version (rules 4–7)

1// WeatherCardEffect.res
2open Units
3open Weather
4
5type status = Loading | Ready | Failed
6
7let rowClass = status =>
8 switch status {
9 | Loading => "temp-row is-loading"
10 | Failed => "temp-row is-failed"
11 | Ready => "temp-row"
12 }
13
14let statusText = status =>
15 switch status {
16 | Loading => "Fetching the current weather…"
17 | Failed => "Couldn't reach the weather service."
18 | Ready => "Live from Open-Meteo."
19 }
20
21@xote.component
22let make = () => {
23 let capital = Signal.make(capitals->Array.getUnsafe(0))
24 let status = Signal.make(Loading)
25 let celsius = Signal.make(0.0)
26 let fahrenheit = Computed.make(() => Signal.get(celsius)->toFahrenheit)
27 let kelvin = Computed.make(() => Signal.get(celsius)->toKelvin)
28
29 if SSRContext.isClient {
30 Effect.run(() => {
31 let current = Signal.get(capital)
32 let stale = ref(false)
33 Signal.set(status, Loading)
34 fetchTemperature(current)
35 ->Promise.thenResolve(temperature =>
36 if !stale.contents {
37 Signal.set(celsius, temperature)
38 Signal.set(status, Ready)
39 }
40 )
41 ->Promise.catch(_ => {
42 if !stale.contents {
43 Signal.set(status, Failed)
44 }
45 Promise.resolve()
46 })
47 ->ignore
48 Some(() => stale := true)
49 })
50 }
51
52 <div>
53 <p> {"Now in "} {Signal.get(capital).name} </p>
54 <div class={rowClass(Signal.get(status))}>
55 <TemperatureDisplay value=celsius unit=Celsius />
56 <TemperatureDisplay value=fahrenheit unit=Fahrenheit />
57 <TemperatureDisplay value=kelvin unit=Kelvin />
58 </div>
59 <p class="status"> {statusText(Signal.get(status))} </p>
60 <button onClick={_ => Signal.update(capital, otherCapital)}> {"Try another capital"} </button>
61 </div>
62}

Weather card, resource version (rules 8–11; 7.2.0)

1// WeatherCardResource.res
2open Units
3open Weather
4
5module LoadingReadouts = {
6 @xote.component
7 let make = () =>
8 <div class="temp-row is-loading" attrs=[("aria-busy", "true")]>
9 <TemperatureDisplay value={Signal.make(0.0)} unit=Celsius />
10 <TemperatureDisplay value={Signal.make(0.0)} unit=Fahrenheit />
11 <TemperatureDisplay value={Signal.make(0.0)} unit=Kelvin />
12 </div>
13}
14
15module Readouts = {
16 @xote.component
17 let make = (~capital: Signal.t<capital>) => {
18 let weather = Resource.make(() => fetchTemperature(Signal.get(capital)))
19 let celsius = Computed.make(() => Signal.get(weather)->Resource.value->Option.getOr(0.0))
20 let fahrenheit = Computed.make(() => Signal.get(celsius)->toFahrenheit)
21 let kelvin = Computed.make(() => Signal.get(celsius)->toKelvin)
22 <div>
23 <div class={Resource.isLoading(Signal.get(weather)) ? "temp-row is-refreshing" : "temp-row"}>
24 <TemperatureDisplay value=celsius unit=Celsius />
25 <TemperatureDisplay value=fahrenheit unit=Fahrenheit />
26 <TemperatureDisplay value=kelvin unit=Kelvin />
27 </div>
28 <p class="status">
29 {switch Signal.get(weather) {
30 | Failed(error) => throw(error)
31 | Refreshing(_) | Pending => "Updating…"
32 | Ready(_) => "Live from Open-Meteo."
33 }}
34 </p>
35 </div>
36 }
37}
38
39@xote.component
40let make = () => {
41 let capital = Signal.make(capitals->Array.getUnsafe(0))
42 <div>
43 <p> {"Now in "} {Signal.get(capital).name} </p>
44 <View.ErrorBoundary
45 fallback={(_error, retry) =>
46 <div class="error">
47 <LoadingReadouts />
48 <div class="error-message">
49 <p> {"Couldn't reach the weather service."} </p>
50 <button onClick={_ => retry()}> {"Try again"} </button>
51 </div>
52 </div>}>
53 <View.Suspense fallback={<LoadingReadouts />}>
54 <Readouts capital />
55 </View.Suspense>
56 </View.ErrorBoundary>
57 <button onClick={_ => Signal.update(capital, otherCapital)}> {"Try another capital"} </button>
58 </div>
59}

Placeholder CSS (rule 7, 11)

1.temp-row.is-loading .temp-value,
2.temp-row.is-failed .temp-value { color: transparent; background: #8883; border-radius: 10px; }
3.temp-row.is-refreshing .temp-value { opacity: 0.4; }
4.status { min-height: 20px; margin: 0; }
5.error { display: grid; }
6.error > * { grid-area: 1 / 1; }
7.error > .temp-row { visibility: hidden; }

Anti-patterns

~value: float on TemperatureDisplay with value={Signal.get(celsius)} → numbers never change after the first render → declare Signal.t<float> and pass the signal.

Swapping the readouts for a loading message with switch status → the card height changes on every load and every capital switch (layout shift) → keep the row, change classes and status text (rule 7).

Reading capital after the await inside a resource fetch:

1let weather = Resource.make(async () => {
2 let _ = await Promise.resolve()
3 await fetchTemperature(Signal.get(capital))
4})

→ capital is not a dependency, so changing it does not refetch → read every dependency before the first await (as in fetchTemperature(Signal.get(capital)), where the argument is evaluated synchronously).

Creating the resource in the parent of View.Suspense → the Suspense does not wait for it, the readouts appear with 0.0 → create it in a component rendered inside the Suspense (rule 8).

Signal.set(capital, pickRandom()) that can pick the current capital → equal value, no notification, nothing reloads → use otherCapital (rule 12).

Edge cases

  • While Suspense waits, its children are already rendered (hidden) behind the fallback; their component bodies, effects and resources run.
  • After the first settle, Suspense never shows its fallback again; refetches surface as Refreshing.
  • retry rebuilds the boundary's subtree from scratch; state owned inside it (the resource) is recreated. State owned outside it (capital) is preserved.
  • Errors thrown in event handlers, timers or promise callbacks are not caught by the boundary; only render/update errors are.
  • Float.toFixed(~digits=1) renders 273.1 for 273.15 (rounding of the binary value); use it only for display.

SSR and hydration

Converter: renders fully on the server. Effect card: server HTML shows the loading state (status Loading, placeholders); the effect runs only after hydration. Resource card: during a server render no fetch starts and the resource stays Pending, so the Suspense fallback (placeholders) is what is rendered; hydration renders the children on the client and fetches.

Verify

Stub fetch and run in jsdom (verified sequence for the resource card): initial render contains is-loading placeholders → after the stubbed response, numbers and "Live from Open-Meteo." → after "Try another capital", is-refreshing with the old numbers and "Updating…" → after a rejecting fetch, the boundary message and "Try again" → after retry, placeholders, then new numbers. The card's height MUST be identical in every state (measure getBoundingClientRect().height).

1globalThis.fetch = async () => ({ json: async () => ({ current_weather: { temperature: 12 } }) })
  • /docs/learn/computeds, /docs/learn/effects — rules 2–6.
  • /docs/learn/async-data — Resource and View.Suspense in full.
  • /docs/learn/lifecycle — View.ErrorBoundary.
  • /docs/guides/fetching-data — more loading patterns.