API
The functions and types @k8ordo/state exports. useAppState is a Client Component hook; everything else runs on the server and in the browser.
On this page
definePageState
Import from @k8ordo/state
Defines page state. url values go in the URL query, entry values in the history entry’s state.
definePageState<Url, Entry>(
key: string,
config: { url?: Url; entry?: Entry },
): PageState<Url, Entry>Parameters
keystring- The state’s name. It is the namespace of the
entryvalues and the store’s registry key. config{ url?: StateSchema; entry?: StateSchema }- The
urlandentryschemas. Pass at least one.
Returns
PageState<Url, Entry> — A definition that both server and client code can import.
Fields
kind'page'- The kind of definition.
useAppStatepicks the store by it. keystring- The key passed as the first argument.
urlUrl- The
urlschema as passed. Hand it to a page’ssearchexport in@k8ordo/framework’s server mode, or to@k8ordo/form’sformFields. entryEntry- The
entryschema as passed. parseUrl(input: UrlInput) => OutputOf<Url>- Reads the
urlvalues. A missing parameter gets its default, and a value the schema rejects falls back to its default field by field. Reading never throws. href(path, values?) => string- Builds a link. A field left out means its default, fields at their default are left out of the query, and Vite’s
baseis prepended. search(values?) => string- Returns the query string alone, without the
?.
Caveats
- Every field needs
.default()or.optional(). Without one, the module throwsfields must tolerate absenceas it loads. - A
urlboolean isz.stringbool()and aurlarray defaults to[]. Any other spelling throws as the module loads. - A field declared in both
urlandentryis a type error, and throwsdeclares in both url and entryat runtime. Passing neither throwsdeclares neither url nor entry.
src/state.tsexport const listState = definePageState('product-list', {
url: z.object({
page: z.coerce.number().int().min(1).default(1),
}),
entry: z.object({
expanded: z.array(z.string()).default([]),
}),
});urlReader
Import from @k8ordo/state
Builds, from a url schema alone, a function that reads a query the way parseUrl does. For code that is handed the schema without its definition.
urlReader<Url extends StateSchema>(
schema: Url,
): (input: UrlInput) => output<Url>Parameters
schemaStateSchema- A
urlschema.
Returns
(input: UrlInput) => output<Url> — A function that reads a query. The reader is built once, when urlReader is called.
Caveats
@k8ordo/framework’s server mode reads the query of a page that exportssearchthrough it.
defineLocalState
Import from @k8ordo/state
Defines state in localStorage. It stays until deleted and is shared by every tab on the device.
defineLocalState<Schema>(
key: string,
schema: Schema,
versioning?: Versioning<Schema>,
): LocalState<Schema>Parameters
keystring- The state’s name.
schemaStateSchema- The schema of the stored values. Its fields follow the same rules as
definePageState’s caveats. versioningVersioning- The
versionandmigratefor a stored shape that has changed. Without it, the stored value is the bare values object.
Returns
LocalState<Schema> — The local state’s definition.
Fields
kind'local'- The kind of definition.
useAppStatepicks the store by it. keystring- The key passed as the first argument.
schemaSchema- The schema as passed.
storageKeystring- The localStorage key the values are written under:
k8ordo-state:<key>. inlineRead() => string- A JavaScript expression for an inline
<script>. In the browser it evaluates to the stored object ornull. Neither the schema normigrateruns.
Caveats
- Values are stored as JSON, so keep fields to what JSON can hold. The schema must accept its own output.
- Writes from other tabs arrive through the
storageevent.
defineSessionState
Import from @k8ordo/state
Defines state in sessionStorage. It survives a reload and goes with the tab.
defineSessionState<Schema>(
key: string,
schema: Schema,
): SessionState<Schema>Parameters
keystring- The state’s name.
schemaStateSchema- The schema of the stored values. Its fields follow the same rules as
definePageState’s caveats.
Returns
SessionState<Schema> — The session state’s definition.
Fields
kind'session'- The kind of definition.
useAppStatepicks the store by it. keystring- The key passed as the first argument.
schemaSchema- The schema as passed.
storageKeystring- The sessionStorage key the values are written under:
k8ordo-state:<key>. inlineRead() => string- A JavaScript expression for an inline
<script>. In the browser it evaluates to the stored object ornull. The schema does not run.
Caveats
- It takes no
versionormigrate. - A
defineLocalStatewith the same key is a different state.
defineCookieState
Import from @k8ordo/state
Defines state in a cookie. The browser writes it, and every request carries it to the server.
defineCookieState<Schema>(
key: string,
schema: Schema,
versioning?: Versioning<Schema>,
): CookieState<Schema>Parameters
keystring- The state’s name. It may hold only letters, digits and the symbols an HTTP token allows. Anything else throws
cannot name a cookieas the module loads. schemaStateSchema- The schema of the stored values. Its fields follow the same rules as
definePageState’s caveats. versioningVersioning- The
versionandmigratefor a stored shape that has changed. Without it, the stored value is the bare values object.
Returns
CookieState<Schema> — The cookie state’s definition.
Fields
kind'cookie'- The kind of definition.
useAppStatepicks the store by it. keystring- The key passed as the first argument.
schemaSchema- The schema as passed.
cookieNamestring- The name of the cookie the values are written under:
k8ordo-state.<key>. parseCookies(cookies: ReadonlyMap<string, string>) => output<Schema>- Reads the values out of a request’s cookies, given as a
Mapof percent-decoded values. In@k8ordo/framework’s server mode, passrequest.cookiesas it is. An older version is migrated as it is read, but never written back. cookieValue(values?) => string- The value for a server writing the same cookie: the values after the schema, as unencoded JSON. A field left out means its default.
Caveats
- The browser writes it with the Cookie Store API, as
Path=/,SameSite=Laxand aMax-Ageof 400 days. The API always addsSecure. - It can never be
HttpOnly. Never put a secret in it. - Over 4 KB, name and value together, the handle
update()returns rejects.
defineMemoryState
Import from @k8ordo/state
Defines state in the JavaScript runtime, with no schema. A reload resets it to the initial values.
defineMemoryState<Values>(
key: string,
initial: Values,
): MemoryState<Values>Parameters
keystring- The state’s name, used as the store’s registry key.
initialValues- The initial values. The type and the set of keys are taken from them, and the server renders them.
Returns
MemoryState<Values> — The memory state’s definition.
Fields
kind'memory'- The kind of definition.
useAppStatepicks the store by it. keystring- The key passed as the first argument.
initialReadonly<Values>- A copy of the initial values.
Caveats
- There is no schema. The values never leave the runtime.
- Replace values through
update(), never by mutating them. Eachupdate()applies on the spot, unbatched.
useAppState
Import from @k8ordo/state
Returns a definition’s current values and the update that changes them. One Client Component hook for every kind of definition.
useAppState(def, options?): [state, update]
useAppState(def, keys, options?): [Pick<state, Key>, update]Parameters
defAnyState- The definition to read and update.
keysreadonly Key[]- The keys to subscribe to. Only a change to one of them re-renders.
[]subscribes to nothing. options{ initialUrl? } | { initialCookie? }- What the server read.
initialUrlis accepted only by a page state withurl,initialCookieonly by a cookie state.
Returns
[state, update] — The current values, and the function that changes them.
Caveats
- A page state’s values are its
urlandentrymerged into one object. - The server render and the hydration render show the defaults. With
initialUrlorinitialCookiethey show those values, and a memory state shows its initial values. update(patch, options?)applies on the spot and returns anUpdateHandle. Except for memory state, the calls made in one handler go out as one write.optionsexists only on page state.- No Provider is needed. The store is created on first use.
pager.tsxconst [{ page }, update] = useAppState(listState, ['page']);
update({ page: page + 1 }, { history: 'push' });UpdateHandle
Import from @k8ordo/state
What update() returns: an object holding two promises, the same shape as navigation.navigate() returns.
type UpdateHandle = {
committed: Promise<void>;
finished: Promise<void>;
};Fields
committedPromise<void>- Resolves once the write has landed: the navigation is committed, or the storage or cookie write has completed.
finishedPromise<void>- Resolves once the router has also finished whatever it does after the write.
Caveats
- Leaving the handle unawaited trips no lint rule, and a rejection never surfaces as an unhandled error.
- A navigation cancelled by a later one rejects with an
AbortError. A write that fails rejects with its error.
UpdateOptions
Import from @k8ordo/state
The second argument of a page state’s update().
type UpdateOptions = {
history?: 'push' | 'replace';
};Fields
history'push' | 'replace''replace'by default.'push'adds a history entry, and only when aurlvalue changes.
Caveats
- No other kind’s
update()takes this argument.
Versioning
Import from @k8ordo/state
The third argument of defineLocalState and defineCookieState.
type Versioning<Schema> = {
version: number;
migrate: (
old: Readonly<Record<string, unknown>>,
fromVersion: number,
) => { readonly [Key in keyof input<Schema>]?: unknown };
};Fields
versionnumber- The current version, a positive integer.
migrate(old, fromVersion) => values- Turns an older version’s values into the current shape.
fromVersionis the version the value was written with,0for a value stored without one.
Caveats
- What it returns passes the schema field by field. A field the schema rejects falls back to its default.
- A
migratethat throws reads as nothing stored. The stored value is left as it is.
Register
Import from @k8ordo/state
The interface an application augments so that the paths href takes are checked by type.
declare module '@k8ordo/state' {
interface Register {
routes: typeof routes;
}
}Fields
routestypeof routes- The type of
@k8ordo/router’s route table. A path is matched against its patterns segment by segment. pathstring- The path union of a router with no table.
routeswins when both are present.
Caveats
- Under
@k8ordo/framework, it is generated into.k8ordo/register.gen.ts. - Augment it only in an application.
- The check is also exported as
RegisteredPath<Path>:Pathwhen accepted,neverwhen refused.
resetStateRegistry
Import from @k8ordo/state
Empties the registry of browser stores. Use it so that state does not carry from one test into the next.
resetStateRegistry(): voidCaveats
- Unmount components first.
- Stored values stay. Delete them by
storageKeyorcookieName.
OutputOf
Import from @k8ordo/state
A schema’s output type. Use it to type the props that carry initialUrl or initialCookie.
type OutputOf<Schema> = Schema extends StateSchema
? output<Schema>
: Record<never, never>;Caveats
- Hand it a definition’s schema, as in
OutputOf<typeof listState.url>. When the schema isundefined, it is an empty object type.
StateSchema
Import from @k8ordo/state
The schema type definitions take. It is what zod’s and zod/mini’s z.object() have in common, so a schema written with either fits.
type StateSchema<Shape extends $ZodShape = $ZodShape> =
$ZodObject<Shape> & { shape: Shape };UrlInput
Import from @k8ordo/state
The query parseUrl and the function from urlReader take: a URLSearchParams, or an object in the shape frameworks hand a page.
type UrlInput =
| URLSearchParams
| Readonly<Record<string, string | readonly string[] | undefined>>;AnyState
Import from @k8ordo/state
The union of every kind of definition. Use it to type a function that takes any of them. Each kind’s own type, PageState and the rest, is exported from the same entry point.
type AnyState =
| PageState
| LocalState
| SessionState
| CookieState
| MemoryState;