Updates
The update() that useAppState returns changes state the same way in every place. You will know when a value reaches the next render and when it is written to its place, and write updates accordingly.
On this page
Changed fields only
const [{ inStock, page }, update] = useAppState(listState);
update({ inStock: true, page: 1 });Pass update() an object with only the fields to change. Every field you leave out keeps its current value.
The values enter the state at once, and the next render shows them. The write to the place happens afterwards, so the screen never waits for the URL or storage.
A field the definition does not declare is a type error. Passed in a way that bypasses the type check, it raises a TypeError such as "product-list" has no field "sort".
Validation on write
update({ page: 0 });
With `page` at `.min(1)`, lands on the default `1`update() runs the merged state through the schema before the next render. A url field is validated the same way as a value read from the URL, so update({ page: 0 }) ends up where opening ?page=0 would.
A value no URL can carry makes the update() call itself fail with a TypeError ending in has no URL serialization. Nothing is written.
A memory state has no schema, so whatever you pass goes in as it is.
replace and push
update({ inStock: true, page: 1 });
Rewrites the current history entry
update({ page: page + 1 }, { history: 'push' });
Adds a new history entryBy default update() rewrites the current history entry. Pass { history: 'push' } only for an update the back button should undo, such as paging.
The option exists only on definePageState’s update(), and takes effect only when a url value changes. An update that changes only entry values rewrites the current history entry in place. If any call in a batch asks for push, the batch’s navigation is a push.
To move to another page, use @k8ordo/router’s navigateTo. It pushes by default.
Writes in one handler
const clear = () => {
update({ inStock: false });
update({ page: 1 });
};Several update() calls in one handler are batched, as setState calls are. The two calls above are one write.
What that one write is depends on the place and on what changed.
- A
urlvalue changes: onenavigation.navigate(), carrying anyentrychanges with it. - Only
entryvalues change: onenavigation.updateCurrentEntry(). - localStorage and sessionStorage: one
setItem. - A cookie: one
cookieStore.set(). - Memory: nothing is batched. Each call applies on the spot and returns a handle of its own, already settled.
Writes that follow one another across handlers, as a slider's do, are thinned out on their way to the URL. A replace that changes a url value waits until 100 ms have passed since the last url write, and the update() calls made meanwhile become one navigation. The value on screen still changes on every update(). This is because WebKit lets a document navigate only 200 times in ten seconds. A { history: 'push' } write never waits.
A page state batch whose result equals the current values neither navigates nor rewrites the history entry. localStorage, sessionStorage and cookies rewrite their stored value even when nothing changed. How parameters of other definitions and of the router are kept is explained on How it works.
committed and finished
const { committed, finished } = update({ page: 2 });update() returns an object holding two promises, the same shape navigation.navigate() returns. It is not a promise itself, so ignoring it does not trip no-floating-promises. Ignoring it is the normal case.
committed: settles once the write is in its place.finished: settles once the router has finished whatever follows the write.
To wait for the write, await finished. Here, focus moves to the heading once the next page is in place.
pager.tsxconst heading = useRef<HTMLHeadingElement>(null);
const onNext = async () => {
await update({ page: page + 1 }, { history: 'push' }).finished;
heading.current?.focus();
};A handle for a write with no navigation behind it settles once the batch is written; a cookie handle once the Cookie Store API has written it. A handle rejects in two cases.
- A navigation overtaken by a later one: an
AbortError, for example when the same handler also writes another page state. A thinned write still waiting when the page is left is not written, and rejects with anAbortErrortoo. A caller that never awaits the handle never sees it. - A failed localStorage, sessionStorage or cookie write: the handle rejects with that error. A full quota, blocked site data, a cookie over 4 KB, or a schema that throws on the values about to be written. The rendered value stays.
Note
An async action can await it the same way: startTransition(async …), useTransition, or @k8ordo/ui’s Button onAction. Under @k8ordo/router, though, a url update issued while another page is still loading is a page change. Its finished settles once that page is on screen, without waiting for the action to end.
Functional updates
update((current) => ({ page: current.page + 1 }));To derive the next value from the current one, pass update() a function. The function receives the batched state, including updates not yet written.
Calling update({ page: page + 1 }) twice in one handler with the page read during render adds one. Written as a function, it adds two.
Key subscriptions
useAppState(listState);
Any field re-renders it
useAppState(listState, ['page']);
Only `page` re-renders it
useAppState(listState, []);
Subscribes to nothing (write-only)
useAppState(listState, ['page'], { initialUrl });
Options come after the key arrayPass useAppState an array of keys as its second argument, and it re-renders only when one of those keys changes. The array can be written inline. It is normalized internally, so useMemo is not needed.
A field that did not change keeps its previous reference, so it goes straight into memo or a dependency array. How fields are compared is explained on How it works.
Give state that changes at very different rates separate definitions. Re-rendering is decided per definition.
Drafts
search-box.tsxexport function SearchBox() {
const [{ q }, update] = useAppState(catalogState, ['q']);
return (
<form
onSubmit={(event) => {
event.preventDefault();
const data = new FormData(event.currentTarget);
update({ q: String(data.get('q') ?? ''), page: 1 });
}}
>
<input defaultValue={q} key={q} name="q" type="search" />
<button type="submit">Search</button>
</form>
);
}Calling update() on every keystroke rewrites the URL once per character. Keep the draft in the DOM or in local React state, and call update() at a commit point such as submit or paging.
key={q} remounts the input with the new defaultValue when q changes from outside, through the back button for example.
For a form that works before JavaScript loads, let a GET form write the URL. Pairing it with @k8ordo/form is covered in “Search forms”.
Pitfall
Do not copy a definition’s values into useState and try to keep them in sync. The copy is not updated by the back button or by other tabs’ writes. Call useAppState wherever the value is needed.
Write log
A real definePageState that rewrites this page’s URL and history entry, with a and b in the URL and c in the entry.
useAppState(def){ a: 0, b: 0, c: 0 }RendersuseAppState(def, ['a']){ a: 0 }RendersuseAppState(def, ['b']){ b: 0 }Renders
Try it
- Press “a + 1”. One line starting with
navigate · replaceis added to the log. Then press “a + 1, three times”:agoes up by 3, yet only one line is added. - Press “c + 1”. The URL stays as it is, and
updateCurrentEntryis added to the log. - Press “b + 1”. The render count of the
['a']subscription stays the same, and only the other two go up. - Press “a = -1”.
abecomes its default0, because the schema rejects negative numbers. - Press “a + 1 (push)”, then the browser’s back button.
areturns to its previous value.