Tutorial: temperature converter
Build a small temperature converter step by step, and meet signals, computeds and effects along the way.
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.res2type tempUnit = Celsius | Fahrenheit | Kelvin34let symbolFor = unit =>5 switch unit {6 | Celsius => "°C"7 | Fahrenheit => "°F"8 | Kelvin => "K"9 }1011let labelFor = unit =>12 switch unit {13 | Celsius => "Celsius"14 | Fahrenheit => "Fahrenheit"15 | Kelvin => "Kelvin"16 }1718@xote.component19let 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.res2View.mountById(<TemperatureDisplay value=22.0 unit=Celsius />, "app")
1@xote.component2let 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>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.component3let 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 same7 </div>
Then a converter component owns the signal and the slider:
1let celsius = Signal.make(22.0)23@get external target: Dom.event => {"value": string} = "target"45let onSlide = evt =>6 switch Float.fromString(target(evt)["value"]) {7 | Some(value) => Signal.set(celsius, value)8 | None => ()9 }1011@xote.component12let make = () =>13 <div>14 <TemperatureDisplay value=celsius unit=Celsius />15 <input16 type_="range"17 min="-20"18 max="40"19 step="0.5"20 value={Signal.get(celsius)->Float.toString}21 onInput=onSlide22 />23 </div>A few things to notice:
- The
@get externalline is a one-line binding that readsevent.target, so the handler can get the slider's value as a string. Signal.setwrites a new value. Everything that readcelsiuswithSignal.getupdates.- 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.
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)45@xote.component6let make = () =>7 <div>8 <TemperatureDisplay value=celsius unit=Celsius />9 <TemperatureDisplay value=fahrenheit unit=Fahrenheit />10 <TemperatureDisplay value=kelvin unit=Kelvin />11 <input12 type_="range"13 min="-20"14 max="40"15 step="0.5"16 value={Signal.get(celsius)->Float.toString}17 onInput=onSlide18 />19 </div>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.res2type capital = {name: string, lat: float, lng: float}34let 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]910let pickCapital = () => capitals->Array.getUnsafe(Math.Int.random(0, Array.length(capitals)))1112let 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}1617type response18type currentWeather = {temperature: float}19type forecast = {current_weather: currentWeather}2021@val external fetch: string => promise<response> = "fetch"22@send external json: response => promise<forecast> = "json"2324let 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}` ++ "¤t_weather=true"29 let response = await fetch(url)30 let forecast = await json(response)31 forecast.current_weather.temperature32}
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.
1open Weather23type status = Loading | Ready | Failed45let rowClass = status =>6 switch status {7 | Loading => "temp-row is-loading"8 | Failed => "temp-row is-failed"9 | Ready => "temp-row"10 }1112let 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 }1819@xote.component20let 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)2627 Effect.run(() => {28 let current = Signal.get(capital)29 let stale = ref(false)30 Signal.set(status, Loading)3132 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 ->ignore4647 Some(() => stale := true)48 })4950 let shuffle = _ => Signal.update(capital, otherCapital)5152 <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}Fetching the current weather…
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,
rowClassaddsis-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 theclassattribute and the status text depend onstatus, 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.2Step 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, thenReady(value),Refreshing(value)while it fetches again, orFailed(error). Signals it reads before its firstawaitare its inputs, so changingcapitalfetches again, and a late answer for an old capital is ignored for you. View.Suspenseshows 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.ErrorBoundarycatches an error thrown while rendering and shows a fallback with aretryfunction. The readouts throw when the resource fails, and the boundary shows a panel the same size as the readouts.
1open Weather23module WeatherReadouts = {4 @xote.component5 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)1011 <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}2728@xote.component29let make = () => {30 let capital = Signal.make(pickCapital())31 let shuffle = _ => Signal.update(capital, otherCapital)3233 <div>34 <h3> {"Now in "} {Signal.get(capital).name} </h3>35 <View.ErrorBoundary36 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}Fetching the current weather…
What changed from step 4:
- The resource replaces the effect, the
statussignal and the stale flag.Resource.maketakes the fetch;Resource.valuereads its result, with0.0until there is one. - The component that creates the resource sits inside the
Suspense. That's what makes the Suspense wait for it.LoadingReadoutsis 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 nearestView.ErrorBoundary. Itsretryrenders 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
| Part | Requires | Version |
|---|---|---|
Converter (Signal, Computed, PPX) | xote, ppx-flags | stable 7.1.0 |
Weather card with Effect.run | xote | stable 7.1.0 |
Weather card with Resource, View.Suspense, View.ErrorBoundary | xote | 7.2.0 (new) |
| Network | fetch (browser or Node 18+), Open-Meteo API (no key) |
Rules
TemperatureDisplaytakes~value: Signal.t<float>, notfloat: user-component props are read once, so afloatprop would freeze (see/docs/thinking-in-signals, rule 13).fahrenheitandkelvinare computeds ofcelsius; they MUST NOT be separate signals kept in sync. A computed is itself aSignal.t, so it can be passed where a signal is expected.- The slider's
valuereadscelsiusin attribute position, so it is a reactive leaf;onInputwritescelsius. Only the three number texts and the slider'svalueupdate on input. - In the effect version, the effect reads
capitalbefore starting the request, socapitalis its only dependency; it writesstatusandcelsius, which it does not read. - 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. - The effect is guarded by
SSRContext.isClientbecause 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. - 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. - In the resource version, the resource is created inside
Readouts, which is rendered underView.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. - On a refetch the resource state is
Refreshing(previous): the previous numbers stay and are dimmed viaResource.isLoading. - A failure is routed to the error boundary by throwing in a reactive leaf:
| Failed(error) => throw(error). The boundary replaces its subtree withfallback;retryrebuilds the subtree, which creates a new resource and fetches again. - 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.
- "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
| Name | Signature | Behaviour |
|---|---|---|
Computed.make | (unit => 'a, ~name: string=?, ~equals: ('a, 'a) => bool=?) => Signal.t<'a> | derived value |
Effect.run | (unit => option<unit => unit>, ~name: string=?) => unit | runs 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.value | Resource.state<'a> => option<'a> | value of Ready/Refreshing |
Resource.isLoading | Resource.state<'a> => bool | true for Pending and Refreshing |
View.Suspense | JSX: <View.Suspense fallback> children </View.Suspense> | fallback until resources below have settled once |
View.ErrorBoundary | JSX: fallback: (exn, unit => unit) => View.node, onError? | catches errors thrown while rendering/updating its subtree |
SSRContext.isClient | bool | true in the browser |
Patterns
Shared helpers
1// Units.res2type tempUnit = Celsius | Fahrenheit | Kelvin34let symbolFor = unit =>5 switch unit {6 | Celsius => "°C"7 | Fahrenheit => "°F"8 | Kelvin => "K"9 }1011let labelFor = unit =>12 switch unit {13 | Celsius => "Celsius"14 | Fahrenheit => "Fahrenheit"15 | Kelvin => "Kelvin"16 }1718let toFahrenheit = celsius => celsius *. 9.0 /. 5.0 +. 32.019let toKelvin = celsius => celsius +. 273.15
1// TemperatureDisplay.res — rule 12open Units34@xote.component5let 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.res2open Units34@get external target: Dom.event => {"value": string} = "target"56let celsius = Signal.make(22.0)7let fahrenheit = Computed.make(() => Signal.get(celsius)->toFahrenheit)8let kelvin = Computed.make(() => Signal.get(celsius)->toKelvin)910let onSlide = (event: Dom.event) =>11 switch Float.fromString(target(event)["value"]) {12 | Some(value) => Signal.set(celsius, value)13 | None => ()14 }1516@xote.component17let 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 <input25 type_="range"26 min="-20"27 max="40"28 step="0.5"29 value={Signal.get(celsius)->Float.toString}30 onInput=onSlide31 />32 </div>
Weather data
1// Weather.res2type capital = {name: string, lat: float, lng: float}34let 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]910// 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}1516type response17type currentWeather = {temperature: float}18type forecast = {current_weather: currentWeather}1920@val external fetch: string => promise<response> = "fetch"21@send external json: response => promise<forecast> = "json"2223let 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}` ++ "¤t_weather=true"28 let response = await fetch(url)29 let forecast = await json(response)30 forecast.current_weather.temperature31}
Weather card, effect version (rules 4–7)
1// WeatherCardEffect.res2open Units3open Weather45type status = Loading | Ready | Failed67let rowClass = status =>8 switch status {9 | Loading => "temp-row is-loading"10 | Failed => "temp-row is-failed"11 | Ready => "temp-row"12 }1314let 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 }2021@xote.component22let 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)2829 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 ->ignore48 Some(() => stale := true)49 })50 }5152 <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.res2open Units3open Weather45module LoadingReadouts = {6 @xote.component7 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}1415module Readouts = {16 @xote.component17 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}3839@xote.component40let make = () => {41 let capital = Signal.make(capitals->Array.getUnsafe(0))42 <div>43 <p> {"Now in "} {Signal.get(capital).name} </p>44 <View.ErrorBoundary45 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. retryrebuilds 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)renders273.1for273.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 } }) })
Related
/docs/learn/computeds,/docs/learn/effects— rules 2–6./docs/learn/async-data—ResourceandView.Suspensein full./docs/learn/lifecycle—View.ErrorBoundary./docs/guides/fetching-data— more loading patterns.