API actions and page mutations
An api action round-trips to your backend. The response can mutate the page: replace a widget, patch a section, toast.
An api action round-trips to your backend. The response can mutate the page: replace a widget, append or prepend sections, remove a widget, replace the page, and optionally toast. There is no patch_section kind. Section changes are append_sections, prepend_sections, or a replace_page. Widget changes are replace_widget and remove_widget.
Flow-UI still performs no HTTP. APIActionHandler asks PageStore.performAction, which calls PageLoader.loadPage with PageRequest.Kind.action and the action’s raw JSON. Your loader already owns URLs, auth, and retries. The package owns decode and apply.
This follows server driven navigation with actions. Deep links leave the page. Sheets present on the page. api stays on the page and changes it. Stable ids from stable widget identities are how replace_widget finds the row.
The handler’s job#
APIActionHandler guards action.type == "api" and a non-nil pageStore. It awaits performAction(payload: action.raw), decodes ActionResponse off the main actor via decodeActionResponse, then applies each instruction.pageMutation. If the response includes toast, the presenter shows it. Cancellation returns true without an error toast, because the page moved on. Other errors show “Something went wrong” and still return true so the action is not logged as unhandled.
Extra keys on the action (endpoint, item, method) are host and backend agreement. The package does not interpret endpoint. Your PageLoader reads request.kind and the JSONValue payload and decides which URL to hit.
ActionResponse shape#
mutations decodes as LossyArray<MutationInstruction>. One bad instruction drops. toast is optional { "message": "Saved" }. The docs page is Mutations.
MutationInstruction switches on kind:
replace_pagepluspageappend_sectionsplussectionsprepend_sectionsplussectionsreplace_widgetplusidandwidgetremove_widgetplusid
Unknown kind strings throw inside that initializer. The lossy list records droppedElement and continues. Old binaries therefore ignore future kinds. That is the same additive story as unknown widgets and schema versioning.
Each instruction exposes pageMutation as the PageMutation enum PageStore.apply consumes.
What PageMutation actually does#
PageModel.apply:
replacePageassigns the whole modelappendSectionsappends tosectionsprependSectionsinserts at index 0replaceWidget(id:with:)swaps the first match in page header widgets, section header, section body, or page footer widgetsremoveWidget(id:)removes from those same locations (section header becomesnilif it matched)
Nested accordion items are not walked. To change a child inside an accordion, replace the accordion widget by its page-level id, or lift the row onto the section. Nested widgets and accordion called this out.
PageStore.apply no-ops if the page is not loaded, except replacePage, which can load from empty. Apply is synchronous after decode. The store writes state = .loaded(page).
replace_widget needs a full widget#
The incoming object is an AnyWidget: type, data, and the rest of the envelope. A partial “patch fields” blob is not a kind. If you want to change one title, send a complete widget with the same id. Widget state for an untouched id survives. A replaced widget starts fresh in WidgetStateStore because it is a new view identity with a reset payload; the store is keyed by id, so the same id keeps stepper state unless you reset. Refresh clears the whole store. A single replace_widget does not call stateStore.reset(). If the replacement is a stepper with a new initial but the same id, the bound count may still be the old one until refresh. Prefer changing id when you want state to re-initialise, or document that counts persist across in-place replace.
That persistence is often what you want for a favourite toggle that does not touch the stepper on the same row. It is surprising if you expected initial to win again.
Choose a kind on purpose#
Favourite a row: replace_widget with the favourited payload, optional toast.
Delete a row: remove_widget.
Load more as a mutation rather than pagination: append_sections. Prefer envelope pagination for infinite lists; mutation append is for “user tapped Load related.”
Insert an alert strip above everything: prepend_sections.
The document is now a different page (nav title, footer, all sections): replace_page. Equivalent to a silent refresh without going through refresh()’s state reset unless you also reset. replace_page does not call stateStore.reset(). If you needed a clean store, send refresh_page instead or reset in a host handler.
Do not replace_page to change one icon. Do not refresh_page to change one icon. Do not deeplink to the same page id to change one icon.
| Kind | Use when |
|---|---|
replace_widget | One row (header, section, or footer) changes |
remove_widget | That row should disappear |
append_sections | New sections at the end |
prepend_sections | New sections at the front |
replace_page | The whole document is different |
Loader and cancellation#
While api is in flight, pagination may also be in flight. appendNextPage re-reads current state after await so a replace_widget that landed during the fetch is not overwritten by a stale capture. If a replace_page happened during pagination, postback mismatch drops the next-page response. Those interactions are PageStore details you should not reimplement in the handler.
cancelInFlight() on the dispatcher prevents a late api from applying on a page the user already left. Hosts that pop should cancel.
Decode of the action response is Task.detached so a large mutation payload does not stall the main actor. The same idea as page decode.
Testing#
Fixture an ActionResponse with one replace_widget. Apply it to a PageModel in a unit test without a loader. Fixture a PageLoader that returns that JSON for .action and tap a widget in UI tests. Assert diagnostics when you send an unknown kind. Assert the error toast when the loader throws.
What the loader must return for .action#
performAction is loadPage with PageRequest.Kind.action. The Data you return is an ActionResponse, not a PageResponse. Returning a full page document here will fail decode, show “Something went wrong”, and consume the action. That looks like a backend outage and is a shape mismatch.
If your HTTP API already returns the updated page for every POST, map it in the loader: wrap a replace_page mutation around the page object, or call refresh from a host handler instead of using api. Do not hope the package will notice a page-shaped blob and swap the document. It will not.
Unknown mutation kinds drop inside LossyArray. A backend that ships patch_section today will not crash last month’s app. It also will not patch. Until the binary knows the kind, use replace_widget or replace_page. There is no built-in field-level patch.
Toast on the response is ToastInstruction.message only. Duration is the presenter default. If you need a long toast, send a separate toast action via redispatch, or override APIActionHandler. The built-in applies mutations first, then the optional response toast, then returns true.
Where this sits#
Mutations and Actions API are the contracts. Server driven navigation with actions is the chain. Stable widget identities is why ids exist. The next concern in this series is the loader seam itself: every api byte still comes from the host.
Round trip the raw action. Apply exact kinds. Toast if the backend said so. No framework HTTP.
Read next#
api is a loader round trip plus PageMutation. The host still fetches. The store still applies.
Related documentation
Related articles
- Navigation6 min read
Bottom sheets described by the backend
`open_bottom_sheet` carries a sheet envelope: detents, header, sections, footer. The client presents native SwiftUI, not a web modal.
- Navigation6 min read
Deep linking through host handlers
Flow-UI does not ship a router. A deeplink action is data. Your app’s handler decides NavigationStack, tabs, or an external URL.
- Navigation8 min read
Server driven navigation with actions
Taps carry declarative actions: toast, sheet, api, deeplink, dismiss, refresh. The dispatcher chains host handlers.
More on the blog.
Read the source
Flow-UI is MIT licensed. The schema, renderer and starter widgets live on GitHub.
GitHubGet started with Flow-UI
Install the Swift package, register a widget, and render a page from JSON.
Get started