On this pageUpdate Defines Message Reactions
Update
The update function defines how the application reacts to incoming Messages. It receives the current Model and a Message, then returns the next Model and any Commands for the runtime to execute. Shared pure transitions can also be expressed as Steps and applied by parent startup operations.
Update is pure. Given the same Model and Message, it returns the same result. It does not mutate state, call browser APIs, start timers, or make requests. That makes a transition direct to test: pass in the inputs and assert on the returned values.
Use Message.match to handle the Message union. If you add a Message and omit its branch, TypeScript reports the missing case. No default branch silently absorbs a new variant.
Use a defineTaggedUnion or defineRouteUnion namespace's match for exhaustive matching and matchOrElse for selected variants with a fallback. Use Effect's Match when one handler matches several tags, for Message partial matching, or for unions without their own matcher. This excerpt remains in the compact Counter's application.ts after its Application declaration.
Each branch describes one transition. ClickedDecrement and ClickedIncrement transform the current count. ClickedReset replaces it with zero. This version of the counter has no side effects, so all three omit commands.
The branches build their next Model with modifyFields. Each named field receives a function from its current value to its next value. Omitted fields keep their existing values and references, so the same update style continues to work as the Model grows.
Update returns a record containing the next Model and, when needed, an array of Commands. A Command describes one side effect, such as an HTTP request, timer, or browser API call. The Commands page adds a delayed reset and puts the optional commands field to work.
Return Commands beside the next Model from the Message branch that requests the work:
ClickedIncrement changes the count and asks the runtime to persist it. CompletedPersistCount records that the Command finished, but it has no more work to request, so that branch omits commands.
FeatureComposition.makeUpdate authors a Block's update and infers the handler services required by the Commands across all parent-owned branches. Registered Bindings route their generated child envelopes before this callback runs.
An authored update supports both call directions. The Runtime calls update(model, message, ...context). Application code can call update(message)(model, ...context) to turn one truthful Message into a Step. The curried form retains the same Command requirements, OutMessage type, and registered graph evidence.
Use the curried form for internal Step composition. A Block's operations record has a narrower purpose: each named operation produces a Message and any update context. Put the local Message constructor directly under operations when the public arguments map directly to its payload. Completion creates the operation without constructing a Message. The completed Block or a registered Binding passes that Message through the Block's update synchronously as part of the pure transition. It does not enqueue another Runtime Message or add a startup phase. The same Message branch owns the child invariant, Model change, Command, and OutMessage. This informRouteChanged operation records that a parent informed the child of a route change:
A constructor-backed operation takes one constructor payload object for a constructor with fields, with constructor defaults honored, followed by the update context. An empty-fields constructor takes no payload placeholder. Use a tuple producer under operations when the public inputs need mapping, refinement, defaults, or an exact context tuple. Inline tuple producers receive context from prepareBlock; use Tuple.make(Message.Fact(...), ...context) when extracting one so TypeScript preserves the tuple. Both forms complete through the same update path and use the update function's complete return contract, including its Command requirements and OutMessage type, even when the selected Message branch returns less. Calling a pure operation does not run effects returned by another branch. Keep standalone and Definition-owned Steps for internal composition that does not form part of the Block's public operation API.
The context rule is exact: update(message)(model, ...context). Update.combineSteps accepts unary Steps, so an update with required dispatch context needs an explicit unary adapter that supplies that context:
Update.defineStep does the same inference for a standalone Step producer. Annotate its Model parameter and let the helper infer the returned Command requirements and OutMessage. Author an OutMessage fold with ParentDefinition.makeOutMessageFold(ChildBlock, handlers) whether the fold is inline in a Binding policy or extracted to a named value. The completed child and parent Definition supply the child payloads, parent Model, result channels, and FoldContext. Callers can compose the returned Steps through Update.combineSteps without naming a service union by hand.
Update.RequirementsOf<typeof update> extracts the inferred handler service union from an update. Use it when a parent or exported type needs to name those requirements. Application assembly reads the requirements from the update return type directly.
An update, init, Step, or component helper that statically creates no Commands omits commands. When it computes a Commands collection, it returns that collection directly without checking whether it is empty. The foldkit/no-empty-commands-array lint rule rejects only a literal commands: [] property.
For custom startup, a registered Binding's init returns a passive recipe that retains toParentModel, the child arguments, and optional parent Commands. Return that recipe directly from makeInit; the Composition interprets it under the registered graph and produces the complete parent Model with the lifted child Commands. The recipe itself has no result fields to unpack. Ordinary eligible startup uses Composition-owned init to assemble child fields and Commands:
import { ApplicationComposition, HomeBinding } from './composition'
const init = ApplicationComposition.makeInit(() =>
HomeBinding.init({
args: [],
toParentModel: home => ({ home }),
}),
)For another ordinary update-like result that already contains a Model and optional Commands or OutMessage, keep it attached to the operation that produced it. Name the value after the operation and use dot access. The same rule applies when a test consumes an update result:
const formSubmit = update(model, Message.SubmittedForm())
expect(formSubmit.model.status).toBe('Submitting')
expect(formSubmit.commands ?? []).toHaveLength(1)When the operation name collides with the function, use a trailing underscore such as init_. Do not destructure or rename model, commands, or outMessage. Dot access does not make an OutMessage impossible to ignore. It keeps the operation and its returned values visibly connected.
Pass optional Commands directly to APIs that accept them, including Command.mapMessages. Use result.commands ?? [] only when the next operation requires an array for spreading, concatenating, execution, or an assertion.
TypeScript rejects this manual composition when the enclosing update returns Update.Return<Model, Message>:
const dialogOpen = openDialog(model)
return {
model: modifyFields(dialogOpen.model, { isSubmitting: () => false }),
// Type error: with exactOptionalPropertyTypes, this property must be
// omitted when dialogOpen.commands is undefined.
commands: dialogOpen.commands,
}Every Foldkit template enables exactOptionalPropertyTypes. With that setting, the optional commands property may be absent. When the property is present, it must contain Commands. dialogOpen.commands has the type Update.Commands<Message> | undefined, so TypeScript rejects commands: dialogOpen.commands.
This error often points to update results being composed by hand. When both operations update the same Model, express them as Steps and compose them with Update.combineSteps:
return Update.combineSteps(model, [
openDialog,
ApplicationDefinition.makeFieldsStep(() => ({
isSubmitting: () => false,
})),
])A child Binding projects init, fold, and every declared operation. Calling a Binding operation returns a connected parent Step that preserves the child's Message mapping, update-wide Command requirements and OutMessage type, OutMessage policy, and Binding requirement. Its Model input requires the exact registered graph, so typed calls with a raw Model fail. Apply one to the contextual Model inside makeUpdate, include it in makeInit startup, or return it from the owner's makeStep producer. Return or compose the connected result intact: its public type exposes no .model or .commands before checked execution and cannot be narrowed to a useful { model } return. The raw recipe exposes only channels produced directly by the child transition. makeUpdate and makeInit resolve the registered OutMessage policy and sibling operations into the final parent Command Message, requirements, and OutMessage channels. Derive an exported parent contract from that Composition-authored update or the completed Block. Definition.makeStep preserves or wraps a connected value. A completed block.operations.operation(model, ...args) carries its own graph, accepts the raw Block Model, dispatches the produced Message through update, and returns the readable executed result. A keyed Binding prepends its key to the operation arguments. Ordinary internal Steps remain directly callable. TypeScript can erase a function result when assigning it to a method that returns void; outside the exact graph, invoking that erased method only constructs and discards passive configuration and executes no child work. Do not treat that structural erasure as a usable execution path or claim that every erasure fails compilation.
The graph requirement is intentional: an ordinary Model type says nothing about whether the Dialog Binding and its OutMessage policy are registered. Migrate a helper that accepts a raw Model into a Definition-owned Step, then return that Step from makeUpdate, list it in makeInit, or compose it with another Step through Update.combineSteps.
import { DialogBinding } from './composition'
// ❌ Apply a connected Binding operation to an ordinary domain Model.
import { type Model } from './model'
export const closeDialog = (model: Model) => DialogBinding.requestClose()(model)Use Update.combineSteps when two or more operations transform the same Model and a later Step should receive the Model produced by an earlier Step. Use the owning Definition's narrow helper when that Step only changes fields:
return Update.combineSteps(model, [
foldDialogClose,
ApplicationDefinition.makeFieldsStep(() => ({
isSubmitting: () => false,
})),
])combineSteps collects the Steps' Commands without executing them. The Runtime forks the batch independently, so an application must not depend on the Commands' execution or completion order.
Do not wrap one Step in Update.combineSteps; call that operation directly.
Declare child startup ownership beside the Bindings and author the parent initializer through its Composition. The plan supplies only parent-owned fields and lists any startup Steps; the Composition assembles initialized child fields and lifted Commands.
For example, a Workspace Block contains Search and Editor Blocks. Their required direct fields use the automatic zero-argument startup policy. The Search and Editor restoration operations are ordinary Steps listed after the parent-owned fields:
import {
WorkspaceComposition,
SearchBinding,
EditorBinding,
} from './composition'
const init = WorkspaceComposition.makeInit(() => ({
model: {
maybeSelectedDocumentId: Option.none(),
maybeOpenedDocumentId: Option.none(),
},
steps: [SearchBinding.requestRestore(), EditorBinding.requestRestore()],
}))The Composition combines the Search and Editor Models with the Workspace Block's own fields. It retains each child's init Commands and appends the Commands returned by the restoration Steps.
The Step array determines the order of Model transitions. In this example, the Search restoration runs first. The Editor restoration receives that updated Model, so it preserves the selected document. Each child's Binding applies its OutMessage policy as part of the Step.
The Step order applies to Model changes. Commands run independently; a later child's Commands do not wait for an earlier child's Commands to finish.
A restoration Step may emit a child OutMessage after the complete parent Model exists. Select a fold through the Binding's withOutMessagePolicy method to handle that fact locally. The fold can update the parent Model and return Commands, and those Commands join the startup result.
Parent init cannot emit an OutMessage. A Binding used from init therefore handles the initial fact locally instead of forwarding it to another parent:
A local fold can report a more complete result than the child's original OutMessage. For example, an end-date picker reports SelectedDate. A date-range Block forwards SelectedEndDate while the start date is absent. Once both dates are known, its local fold reports CompletedRange instead:
When the selected fold returns CompletedRange, Foldkit uses it and skips the selected forward for that dispatch. When the fold returns no OutMessage, forward supplies SelectedEndDate. A child that emits nothing triggers neither handler.
Use Update.Return<Model, Message> for an update that cannot emit an OutMessage. It prevents a result containing an OutMessage from entering code that would keep only its Model and Commands:
const childUpdate: Update.ReturnWithOutMessage<
typeof Child.ChildBlock.Model.Type,
typeof Child.ChildBlock.Message.Type,
typeof Child.ChildBlock.OutMessage.Type
> = Child.ChildBlock.update(model.child, message)
// Type error: childUpdate may contain an OutMessage that this type cannot hold.
const plainChildUpdate: Update.Return<
typeof Child.ChildBlock.Model.Type,
typeof Child.ChildBlock.Message.Type
> = childUpdateOtherwise, that OutMessage would be lost.
A result with no outMessage can still be used where Update.ReturnWithOutMessage<Model, Message, OutMessage> is expected:
const plainUpdate: Update.Return<typeof Model.Type, Message> = { model }
const blockUpdate: Update.ReturnWithOutMessage<
typeof Model.Type,
Message,
OutMessage
> = plainUpdateThe missing field means this update emitted no OutMessage.
When the OutMessage is already known while constructing a new result, include it directly:
return { model, outMessage: OutMessage.Closed() }For a reusable Step whose only job is to emit a known OutMessage while preserving the Model, use the owning Definition's makeOutMessageStep helper. Ordinary update branches can keep returning the result directly.
Use Update.withOutMessage when attaching an OutMessage to an existing plain result or when the value has the type OutMessage | undefined. If an operation already produced the plain result, pipe that named result into the helper:
const dialogClose = closeDialog(model)
return pipe(dialogClose, Update.withOutMessage(outMessage))The object-spread alternative is easy to get wrong:
// Avoid: this writes outMessage: undefined and accepts a result that already has an OutMessage.
return { ...dialogClose, outMessage }Update.withOutMessage preserves dialogClose.model and dialogClose.commands. A defined value becomes outMessage; undefined leaves the property out. The update result must be a plain return, so the helper cannot overwrite an OutMessage another operation emitted.
When constructing the plain result in the same expression and the value has the type OutMessage | undefined, pass the result first: Update.withOutMessage({ model, commands }, outMessage).