Skip to content

HTTP

For HTTP, use the built-in fetch driver instead of calling fetch in a component. Register it once on the root component:

App.jsx
import { makeFetchDriver } from 'sygnal'
App.drivers = { HTTP: makeFetchDriver() }

A model entry sends a request to the HTTP sink and names the actions that receive the reply: ok for a 2xx response, error for everything else. The intent has no line for the reply.

In this demo, a stand-in server answers: quote 1 slowly, and quote 2 with a 404.

Demo server
const quotes = { 1: { id: 1, text: 'Start where you are.' } }
export default {
'GET /api/quotes/:id': ({ params }) => (quotes[params.id]
? { json: quotes[params.id], delayMs: 1500 }
: { status: 404, json: { message: 'No such quote' }, delayMs: 400 }),
}
Quote.jsx
import { ABORT } from 'sygnal'
function Quote({ state }) {
return (
<div className="quote">
<button className="pick" data={{ id: 1 }}>First</button>
<button className="pick" data={{ id: 2 }}>Second</button>
<button className="refresh">Refresh</button>
<p className="text">{state.status === 'loading' ? 'Loading…' : state.error || state.quote?.text}</p>
</div>
)
}
Quote.initialState = { id: null, status: 'idle', quote: null, error: '' }
Quote.intent = ({ DOM }) => ({
SHOW: DOM.click('.pick').data('id', Number),
REFRESH: DOM.click('.refresh'),
})
Quote.model = {
SHOW: {
STATE: (state, id) => ({ ...state, id, status: 'loading', error: '' }),
HTTP: (state, id) => ({ url: `/api/quotes/${id}`, ok: 'LOADED', error: 'FAILED', latest: true }), // or state.id: STATE has stored it
},
REFRESH: {
STATE: (state) => (state.id === null ? ABORT : { ...state, status: 'loading', error: '' }),
HTTP: (state) => (state.id === null ? ABORT : { url: `/api/quotes/${state.id}`, ok: 'LOADED', error: 'FAILED', latest: true }),
},
LOADED: (state, quote) => ({ ...state, status: 'done', quote }), // the parsed body
FAILED: (state, { status }) => ({ ...state, status: 'error', error: status === 404 ? 'No such quote.' : 'Could not load the quote.' }),
}

Click First, then Second before quote 1 arrives: with latest: true the first request is aborted (see Only the Latest Response), and the 404 goes to FAILED.

  • The ok action gets the parsed body: JSON when the response says so, otherwise text (see parse below).
  • The error action gets { error, status, body, headers, request }. For a non-2xx response, status, the parsed body and the response’s headers are set and error.message reads like 'HTTP 404 Not Found: /api/quotes/9'. For a network error, a body that doesn’t parse, a timeout (error.name === 'TimeoutError') or no fetch, status is undefined. request is the request as the model sent it.
  • The reply goes to exactly the component instance that sent the request. Two <Quote> components, or every item of a Collection, can use the same action names without seeing each other’s replies, and need no request ids.
  • If the instance is removed (a Collection item deleted, a page left), its requests are aborted and nothing arrives.
  • A name with no model entry is reported as SYG112, with the closest model key (or the ancestor that has an entry of that name). A request with a then or catch key is not sent (SYG610): use ok and error.

Because a reply only goes to its sender, a child can’t reuse its parent’s reply actions: a “Try again” button that sends the parent’s request with ok: 'TEMPLATES' gets SYG112, since the button’s own model has no TEMPLATES entry. Two ways to share a loader:

  • Declare it once as a resource where the data is shown, tagged, and re-request it from any component with { invalidate: tag }: every mounted resource with that tag refetches, and nobody needs reply actions.
  • Hand the request to the owner. The child emits EVENTS: event('RETRY_TEMPLATES'); the owner selects it in its intent and sends the request from that entry, so the reply comes back to the owner.
Start.jsx
function Retry() {
return <button className="retry">Try again</button>
}
Retry.intent = ({ DOM }) => ({ RETRY: DOM.click('.retry') })
Retry.model = { RETRY: { HTTP: () => ({ invalidate: 'templates' }) } }
function Start({ state }) {
const { status, data } = state.templates
return (
<div>
{status === 'error' ? <Retry /> : <ul>{(data || []).map((t) => <li key={t.id}>{t.name}</li>)}</ul>}
</div>
)
}
Start.initialState = {}
Start.resources = { templates: () => ({ url: '/api/templates', tags: ['templates'] }) }

STATE runs first, so the HTTP sink of SHOW sees the id STATE just stored; the action’s data has it too. REFRESH doesn’t change id and reads it from state. A request that needs a value STATE replaced (a cleared field, a guard on a flag STATE sets) reads it from the fourth argument’s previousState (Model). Sygnal 6.x gave every sink the state from before the action; see Migrating to 7.0.

Responses arrive in the order the server answers, not the order the requests were sent. With latest: true, sending a request aborts this instance’s earlier requests with the same key that are still in flight, and their replies never arrive. The abort happens when the newer request is sent: a reply that lands before that still arrives. For example, with a debounce in front of the request, an older reply that comes back while the user is still typing (the newer request isn’t sent yet) is delivered, so a reducer that must ignore it needs its own check, such as comparing the reply with the current input. The key is the ok action (else the error action), or an explicit key. A search box needs no request ids and no stale checks. In this demo, a stand-in server searches a few book titles, taking most of a second:

Demo server
const books = ['Dune', 'Dune Messiah', 'Children of Dune', 'Foundation', 'Solaris']
export default {
'GET /api/search': ({ query }) => {
const q = query.q.toLowerCase()
const results = books.filter(b => b.toLowerCase().includes(q)).map(title => ({ title }))
return { json: { results }, delayMs: 900 }
},
}
Search.jsx
import { ABORT, debounce } from 'sygnal'
function Search({ state }) {
return <div><input className="q" aria-label="Search" value={state.query} /><p className="status">{state.status}</p><ul>{state.results.map(r => <li>{r.title}</li>)}</ul></div>
}
Search.initialState = { query: '', status: '', results: [] }
Search.intent = ({ DOM }) => ({
TYPE: DOM.input('.q').value(),
SEARCH: DOM.input('.q').value().compose(debounce(300)).filter(q => q !== ''),
})
Search.model = {
TYPE: {
STATE: (state, query) => (query === '' ? { ...state, query, status: '', results: [] } : { ...state, query }),
HTTP: (state, query) => (query === '' ? { abort: 'RESULTS' } : ABORT), // clearing cancels the request in flight
},
SEARCH: {
STATE: (state) => ({ ...state, status: 'Searching…' }),
HTTP: (state, q) => ({ url: '/api/search', query: { q }, ok: 'RESULTS', error: 'FAILED', latest: true }),
},
RESULTS: (state, body) => ({ ...state, status: '', results: body.results }),
FAILED: (state, { status }) => ({ ...state, status: status === 404 ? 'Not found.' : 'Search failed.', results: [] }),
}
  • Cancel without sending: { abort: 'RESULTS' } aborts this instance’s requests in flight whose key is 'RESULTS'; { abort: true, key: 'search' } does the same for an explicit key. Nothing is delivered for a cancelled request.
  • key groups requests with different reply actions, or splits one action into separate groups: { url: `/api/items/${id}`, ok: 'ITEM', key: `item-${id}`, latest: true } keeps one request per item in flight.
  • makeFetchDriver({ latest: true }) makes every request latest-only (a request can still say latest: false). Prefer latest: true on the request: tests see it too.

A request is an object (or a URL string, for a plain GET with no reply actions):

FieldDefaultMeaning
url(required)The URL, prefixed with the driver’s baseUrl
ok—Action that receives the parsed body of a 2xx response (with stream: the end)
error—Action that receives { error, status, body, headers, request }
keythe ok action, else error, else chunkThe group for latest and abort
method'POST' with json/multipart/body, else 'GET'HTTP method
query—Object appended as a query string, before any #fragment: { q: 'dune' } → ?q=dune (URL-encoded; null/undefined values skipped; an array repeats the key: { tag: ['a', 'b'] } → ?tag=a&tag=b)
json—Body sent as JSON.stringify(json) with Content-Type: application/json
multipart—A multipart/form-data body written as data: { file: state.file, title: state.title } (uploads)
body—Raw body (string, FormData, Blob, …)
progress—Report upload and download progress: an action name ('UPLOADING') or true for HTTP.progress() (Upload and download progress)
stream, chunk, done, meta—Read the body piece by piece: stream: 'sse' | 'ndjson' | 'text', each piece to the chunk action, done the piece that ends it, meta: true SSE pieces as { data, id, event } (Streamed responses)
headers—Object or Headers, merged over the driver’s headers case-insensitively (sent with lowercase names)
latestdriver’s latest (false)Abort this instance’s requests with the same key still in flight
timeoutMsdriver’s timeoutMs (none)Fail with a TimeoutError after this many ms (with stream: if no byte has arrived by then)
parse'auto'How the body becomes the ok data: 'auto' (JSON when the content-type says JSON, otherwise text; 204 → null), 'json', 'text', 'response' (the Response itself), or a function res => value (Response headers)
initdriver’s initOther fetch() options: { credentials: 'include', mode, cache, redirect, referrer, referrerPolicy, integrity, keepalive, priority }
cache, staleTime—Answer from the driver’s cache (GET/HEAD only): see Resources and Caching
keepHeaders—Response headers a resource keeps next to data (and the cache with its entry): ['X-Computed-At'] → state.report.headers['x-computed-at'] (Response headers)
tags, invalidates—Tags for invalidation; invalidates: ['quotes'] refreshes the tagged reads after a 2xx reply
invalidateOndriver’s invalidateOn ('success')'settled': invalidates runs after a failure too, once and not after an abort (Invalidation)
updates—After a 2xx reply, write it into this component’s resources (and their cache entries): updates: 'item', or { items: (list, reply) => newList } (Writing a reply into the cache)
retrydriver’s retry for GET/HEAD (0)Retry network errors, 408, 429 and 5xx: a count or { count, delayMs, maxDelayMs, jitter } (Retries)
validate—A Standard Schema the body must pass (Validation)
batch, combine, split—One reply from several fetches: batch sends these requests in parallel instead (each inherits this request’s fields; its own json, body, parse win), combine(bodies, requests) merges their parsed bodies into the reply, and split(request, error) returns the requests to try instead when one fails (at most 3 deep). decide() sets them for large question sets; the test fake answers such a request as one

Any other field is yours (an id, the query text): it isn’t sent, and it comes back on the failure’s request. A sink that returns ABORT, null or undefined sends nothing.

A request that names only ok sends its failures to HTTP.errors() (logged when nothing listens), and one that names only error sends its successes to HTTP.select(). Name both.

Add progress to a request to hear how far it has got. With an action name, each step arrives as that action of the component that sent it, like ok and error:

Demo server
export default {
'POST /api/files': ({ body }) => {
const file = body.get('file')
return { status: 201, json: { name: file.name, size: file.size }, delayMs: 300 }
},
}
Upload.jsx
import { ABORT } from 'sygnal'
function Upload({ state }) {
const percent = Math.round(state.fraction * 100)
return (
<form className="upload">
<input type="file" className="file" aria-label="File to upload" />
<button type="button" className="sample">Use a 3 MB sample</button>
<button type="submit" disabled={!state.file || state.status === 'uploading'}>Upload</button>
<progress max="100" value={percent} aria-label="Upload progress">{percent}%</progress>
<p className="status" role="status">{state.message}</p>
</form>
)
}
Upload.initialState = { file: null, fraction: 0, status: 'idle', message: '' }
Upload.intent = ({ DOM }) => ({
PICK: DOM.select('.file').events('change').map((e) => e.target.files[0] ?? null),
SAMPLE: DOM.click('.sample'),
SEND: DOM.select('.upload').events('submit', { preventDefault: true }),
})
const busy = (state) => !state.file || state.status === 'uploading'
Upload.model = {
PICK: (state, file) => ({ ...state, file, fraction: 0, status: 'idle', message: file ? file.name : '' }),
SAMPLE: (state) => ({ ...state, file: new File([new Uint8Array(3 * 1024 * 1024)], 'sample.bin'), fraction: 0, status: 'idle', message: 'sample.bin' }),
SEND: {
STATE: (state) => (busy(state) ? ABORT : { ...state, status: 'uploading', fraction: 0, message: 'Uploading…' }),
// STATE has already set status 'uploading': admit the upload by the state before this SEND
HTTP: (state, data, next, { previousState }) => (busy(previousState) ? ABORT : { url: '/api/files', multipart: { file: state.file }, progress: 'UPLOADING', ok: 'UPLOADED', error: 'FAILED' }),
},
UPLOADING: (state, { phase, fraction }) => (phase === 'upload' ? { ...state, fraction } : ABORT),
UPLOADED: (state, saved) => ({ ...state, status: 'done', fraction: 1, message: `Uploaded ${saved.name} (${saved.size} bytes).` }),
FAILED: (state) => ({ ...state, status: 'failed', message: 'Upload failed.' }),
}
  • Each step is { phase, loaded, total, fraction, category, request }. phase is 'upload' while the body is sent, then 'download' while the reply arrives (a GET reports only 'download'). total and fraction (0 to 1) are null when the size isn’t known, such as a download without a Content-Length.
  • How often: at most one step every 50 ms per phase, always including the first and the last (fraction: 1), so a fast connection doesn’t render hundreds of times. A retry starts again at 0.
  • progress: true sends the steps to the source instead: HTTP.progress('upload') in the intent, filtered by category like select().
  • The file comes from the input’s change event (e.target.files) and is kept in state. multipart turns the request’s parts into a multipart/form-data body, the encoding upload endpoints expect: a File or Blob is a file part, an array repeats the name (files: [a, b]), null and undefined are left out, an object is sent as JSON text and anything else as a string. The browser writes the Content-Type with its boundary, so one set in headers is dropped. In a test, t.requests('HTTP') shows the parts as you wrote them (multipart.file.name). An endpoint that takes the raw bytes needs no encoding: body: state.file (with method: 'PUT'). With the form behavior, a file input is a field like any other, and request: { url } sends the submit as multipart with progress in state.form.progress (file fields).
  • XMLHttpRequest: a request with progress goes over XMLHttpRequest, because it is the only way to see upload progress in every browser (streamed fetch uploads work only in Chromium over HTTP/2). The reply is the same as with fetch: parsing, statuses, latest, abort, timeoutMs and retry all apply. Options fetch has and XMLHttpRequest doesn’t (init.keepalive, priority, cache, redirect, integrity, mode) are ignored (SYG636), and the driver’s fetch option isn’t used: put auth in headers, which apply to both. progress does nothing on resources and batch requests. Where there is no XMLHttpRequest (Node, a service worker), the request is sent with fetch and reports no steps.

In a test, t.progress sends a step of a pending request, which stays pending until t.respond or t.fail:

t.simulateEvent('.sample', 'click')
t.simulateEvent('.upload', 'submit')
await t.progress('HTTP', { loaded: 50, total: 100 }, 'UPLOADING') // phase: 'upload' for a request with a body
expect(t.state.fraction).toBe(0.5)
await t.respond('HTTP', { name: 'sample.bin', size: 3145728 }, 'UPLOADED')
expect(t.state.status).toBe('done')

Some endpoints answer a POST with a body that arrives bit by bit: an assistant writing data: {...} lines as it thinks, an export sending one JSON line per row. Add stream to the request and name a chunk action: each piece arrives as that action as soon as it is read, and ok comes at the end. In this demo, a stand-in server answers a question with Server-Sent Events and ends with data: [DONE]:

Demo server
export default {
'POST /api/copilot': ({ json }) => {
const words = `You asked: ${json.q} A streamed answer arrives one piece at a time.`.split(' ')
return { sse: [...words.map((w, i) => ({ text: (i ? ' ' : '') + w })), '[DONE]'], chunkMs: 120 }
},
}
Copilot.jsx
function Copilot({ state }) {
return (
<form className="copilot">
<input className="q" aria-label="Question" value={state.q} />
<button type="submit">Ask</button>
<button type="button" className="stop" disabled={state.status !== 'streaming'}>Stop</button>
<p className="answer" aria-live="polite">{state.answer}</p>
<p className="status">{state.status}</p>
</form>
)
}
Copilot.initialState = { q: 'What is a stream?', answer: '', status: 'idle' }
Copilot.intent = ({ DOM }) => ({
TYPE: DOM.input('.q').value(),
ASK: DOM.select('.copilot').events('submit', { preventDefault: true }),
STOP: DOM.click('.stop'),
})
Copilot.model = {
TYPE: (state, q) => ({ ...state, q }),
ASK: {
STATE: (state) => ({ ...state, answer: '', status: 'streaming' }),
HTTP: (state) => ({
url: '/api/copilot', json: { q: state.q },
stream: 'sse', done: '[DONE]',
chunk: 'DELTA', ok: 'DONE', error: 'FAILED', latest: true,
}),
},
STOP: {
STATE: (state) => ({ ...state, status: 'stopped' }),
HTTP: () => ({ abort: 'DONE' }), // the request's key: its ok action
},
DELTA: (state, piece) => ({ ...state, answer: state.answer + piece.text }),
DONE: (state) => ({ ...state, status: 'done' }),
FAILED: (state) => ({ ...state, status: 'failed' }),
}
  • What a piece is, by stream: 'sse' gives each event’s data, JSON-parsed when it parses (else the text), of every event type; 'ndjson' gives each non-blank line, parsed (a line that isn’t JSON fails the request); 'text' gives the text as it arrives, in whatever chunks the network delivers.
  • The end is the end of the body, or the piece done names: a string compared with the raw piece (done: '[DONE]' for data: [DONE]), or a predicate of the piece as delivered (done: (p) => p.type === 'finish'). There is no default: an endpoint that ends with a sentinel needs done. That piece isn’t delivered, the connection is closed, and ok follows with { status, headers } of the response.
  • meta: true (SSE only) delivers each piece as { data, id, event }, as a socket SSE connection’s meta does: data parsed as above, id the last event id ('' when none was sent) and event the type ('message', or the named event’s name). Use it when the server names its events (event: tool) or numbers them. NDJSON lines and text have no ids or types, so meta is ignored there.
  • Failures: a non-2xx status goes to error like any request, with status, body and headers; so does a connection lost mid-stream, after the pieces read so far.
  • What applies: latest, { abort }, key and removing the component stop the stream, and nothing more arrives from it. timeoutMs is the time to the first byte: a stream that has started never times out. retry, the cache, parse, validate and progress don’t apply, and resources don’t stream.
  • Without a chunk action, each piece is a reply on HTTP.select(category); the end then adds nothing there.
  • For an AI chat UI with tools and messages, the chat driver already reads the providers’ formats; stream is for your own endpoints. A GET stream that stays open, with reconnects, is a socket connection.

In a test, t.push writes a piece to the pending stream request, in its format (an object as JSON), and t.respond ends it:

t.simulateEvent('.copilot', 'submit')
await t.push('HTTP', { text: 'Streams' }) // data: {"text":"Streams"}
await t.push('HTTP', { text: ' arrive' })
expect(t.state.answer).toBe('Streams arrive')
await t.respond('HTTP', null) // the end of the body: DONE
expect(t.state.status).toBe('done')

t.push('HTTP', piece, { event: 'tool', id: 7 }) writes an SSE piece’s event: and id: lines (for meta: true). t.push('HTTP', '[DONE]') ends it through the done piece instead, and t.fail('HTTP', 'connection reset') after a piece loses the connection mid-stream. t.respond with a value other than null writes it as a last piece first.

A failure carries the response’s headers: the error action and HTTP.errors() get headers (a Headers), and the Error has them too (error.headers, so a resource’s state.quote.error.headers). They are set whenever a response came back: a non-2xx status, or a 2xx whose body doesn’t parse or validate. A network error or a timeout has none.

Quote.model = {
FAILED: (state, { status, headers }) => ({
...state,
error: status === 429 ? `Busy: try again in ${headers.get('Retry-After')} s.` : 'Could not load the quote.',
}),
}

On success, name the headers to keep: keepHeaders: ['X-Computed-At'] puts them next to data in a resource’s state, as state.report.headers['x-computed-at'] (names lowercased; null when the response didn’t send one). They work with the query cache, so a cached read shows the headers it was fetched with (Showing when the data was computed):

Report.resources = {
report: () => ({ url: '/api/report', keepHeaders: ['X-Computed-At'] }),
}
// state.report is { status: 'success', data, headers: { 'x-computed-at': '2026-11-01T10:00:00Z' } }
  • A refetch keeps the previous headers with data until its reply lands (keepPrevious too); a new request’s 'loading' clears them.
  • keepHeaders is part of what is fetched: changing it is a new request, and it is part of the cache key.
  • The ok action of a request with reply actions still gets the body. To read any part of the Response there, use a parse function: parse: async (res) => ({ body: await res.json(), asOf: res.headers.get('X-Computed-At') }). A request with a parse function is never cached, since the cache key can’t tell two functions apart.
  • In a test, answer with a real Response to give it headers: t.respond('HTTP', new Response(JSON.stringify(body), { headers: { 'content-type': 'application/json', 'X-Computed-At': '…' } }), 'report').
makeFetchDriver({
baseUrl: '/api', // prefix for every url
headers: { Authorization: `Bearer ${token}` },
init: { credentials: 'include' }, // fetch() options for every request
latest: false, // default for every request
timeoutMs: 10000, // default for every request (default: none)
parse: 'auto', // default for every request
fetch: myFetch, // default: globalThis.fetch, read at each request
cache: queryCache(), // the query cache (default: none), see Resources and Caching
retry: 2, // default for GET/HEAD requests (default: 0)
XMLHttpRequest: MyXhr, // for progress requests (default: the global one)
})
  • Disposing the app (or a hot reload) aborts every request in flight; nothing is delivered after.
  • Server rendering (renderToString, Vike, Astro) runs views only, so no request is made on the server; drivers run on the client. Server data for the first render comes from Vike’s +data or hydrateState, and resources can be rendered from a seeded query cache (Server rendering).

renderComponent needs no driver for HTTP. The requests the component sends are recorded, and the source is a fake that replies like the real driver. Answer a request with t.respond or fail it with t.fail, and await the call:

import { it, expect, afterEach } from 'vitest'
import { renderComponent } from 'sygnal'
import Quote from './Quote.jsx'
let t
afterEach(() => t?.dispose())
it('shows the picked quote, then a missing one', async () => {
t = renderComponent(Quote, { strict: true })
t.simulateEvent('.pick[data-id="2"]', 'click')
await t.respond('HTTP', { text: 'Two' }, 'LOADED') // resolves once LOADED is reduced and rendered
expect(t.requests('HTTP')[0].url).toBe('/api/quotes/2')
expect(t.html()).toContain('Two')
t.simulateEvent('.refresh', 'click')
await t.fail('HTTP', 404) // an HTTP status, an Error, or a message
expect(t.state.error).toBe('No such quote.')
t.expectNoDiagnostics()
})
  • The third argument picks the request: an action, key or category name ('LOADED'), a partial request ({ url: '/api/quotes/2' }), or a predicate. Without it, the newest pending request is answered.
  • A request that was superseded by latest: true or aborted is no longer pending, and answering it throws at the call: expect(() => t.respond('HTTP', [], { query: { q: 'du' } })).toThrow() asserts that a stale request can’t land. (A call made while earlier input is still queued, such as a debounced search, waits up to 1 s for its request instead.)
  • t.requests('HTTP') lists the requests sent; t.sinkValues('HTTP') also has the { abort }, { invalidate } and { reset } commands.
  • A streamed response gets its pieces from t.push('HTTP', piece), then t.respond ends it.

The Testing guide has the full matching rules. In a running app, a sink with no driver is reported as SYG609 (with the dev diagnostics on).

For data a component shows, declare it instead of loading it in the model: Quote.resources = { quote: (state) => state.id && `/api/quotes/${state.id}` } fetches whenever the request changes and writes state.quote = { status, data, error, refreshing }. Resources and Caching covers refetching, the opt-in cache, invalidation, retries and validation.

Requests Without Reply Actions: select() and errors()

Section titled “Requests Without Reply Actions: select() and errors()”

A request without ok/error has no reply actions: its reply goes to the HTTP source, read in the intent with HTTP.select(category) ({ category, value, status, request }) and HTTP.errors(category) ({ error, category, request, status, body, headers }). Use it to compose replies as streams, or for replies that a component other than the sender handles. Reading your own request back this way is the alternative form of reply actions, flagged in strict mode as SYG508.

Change the state at once and send the write in the same action. Put the previous value on the request as your own field: fields the driver doesn’t know aren’t sent, and they come back on the failure’s request, so the error action can restore it. In this demo, a stand-in server saves the first todo and refuses the second:

Demo server
const todos = { 1: { id: 1, title: 'Write', done: false } } // no todo 2: a 500
export default {
'PATCH /api/todos/:id': ({ params, json }) => {
const todo = todos[params.id]
if (!todo) return { status: 500, json: { message: 'Disk full' }, delayMs: 1000 }
return { json: Object.assign(todo, json), delayMs: 1000 }
},
}
Todos.jsx
function Todos({ state }) {
return (
<div>
<ul>{state.todos.map(t => <li className={t.done ? 'todo done' : 'todo'}><button className="toggle" data-id={String(t.id)}>{t.done ? '✓ ' : ''}{t.title}</button></li>)}</ul>
<p className="error">{state.error}</p>
</div>
)
}
Todos.initialState = { todos: [{ id: 1, title: 'Write', done: false }, { id: 2, title: 'Ship', done: false }], error: '' }
Todos.intent = ({ DOM }) => ({ TOGGLE: DOM.click('.toggle').data('id', Number) })
Todos.model = {
TOGGLE: {
STATE: (state, id) => ({ ...state, error: '', todos: state.todos.map(t => (t.id === id ? { ...t, done: !t.done } : t)) }),
HTTP: (state, id, next, { previousState }) => {
const before = previousState.todos.find(t => t.id === id) // rollback value
const updated = state.todos.find(t => t.id === id)
return { url: `/api/todos/${id}`, method: 'PATCH', json: { done: updated.done }, ok: 'SAVED', error: 'SAVE_FAILED', before }
},
},
SAVED: (state, saved) => ({ ...state, todos: state.todos.map(t => (t.id === saved.id ? saved : t)) }),
SAVE_FAILED: (state, { request }) => ({ // request is the request as sent, with your own fields
...state,
error: 'Could not save.',
todos: state.todos.map(t => (t.id === request.before.id ? request.before : t)),
}),
}

SAVED replaces the item with the server’s version. In a test, await t.fail('HTTP', 500) and check that the item is back.

A write’s status is ordinary state: set it when the request is sent and in the reply actions. Ignoring a second click while saving keeps one request in flight. In this demo, a stand-in server rejects an empty name:

Demo server
export default {
'PUT /api/profile': ({ json }) => (json.name.trim() === ''
? { status: 422, json: { name: 'Required' }, delayMs: 800 }
: { json, delayMs: 800 }),
}
Profile.jsx
import { ABORT } from 'sygnal'
function Profile({ state }) {
const label = { idle: '', saving: 'Saving…', saved: 'Saved.', failed: 'Could not save.' }[state.save]
return (
<form>
<input className="name" aria-label="Name" value={state.name} />
<button className="save" disabled={state.save === 'saving'}>Save</button>
<p className="save-status">{label}</p>
</form>
)
}
Profile.initialState = { name: '', save: 'idle' } // 'idle' | 'saving' | 'saved' | 'failed'
Profile.intent = ({ DOM }) => ({ NAME: DOM.input('.name').value(), SAVE: DOM.click('.save') })
Profile.model = {
NAME: (state, name) => ({ ...state, name, save: 'idle' }),
SAVE: {
STATE: (state) => (state.save === 'saving' ? ABORT : { ...state, save: 'saving' }),
HTTP: (state, data, next, { previousState }) => (previousState.save === 'saving' ? ABORT : { url: '/api/profile', method: 'PUT', json: { name: state.name }, ok: 'SAVED', error: 'SAVE_FAILED' }),
},
SAVED: (state) => ({ ...state, save: 'saved' }),
SAVE_FAILED: (state) => ({ ...state, save: 'failed' }),
}

To refresh the reads a save changed, add invalidates: ['profile'] to the request (Invalidation). To show the saved record at once, add updates: 'profile' when the profile is a resource (Writing a reply into the cache).

For reads, see the pagination and infinite list recipes.

  • Resources and Caching: declarative reads, the query cache, invalidation, retries, validation
  • Sockets: WebSocket and server-sent events with makeSocketDriver()
  • Typed APIs: requests built from an API contract (oRPC, OpenAPI, Hono), with typed replies and errors (experimental)
  • Custom Drivers: driverFromAsync() for any promise-returning function, and hand-written drivers
  • Server Functions: calling Telefunc functions through a driver with reply actions
  • AI Chat: the chat driver, whose requests and reply actions work like these, with streamed text
  • AI Decisions: decide() builds a request for this driver, for typed answers from a decision model