@k8ordo/state

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.

ts
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 entry values and the store’s registry key.
config{ url?: StateSchema; entry?: StateSchema }
The url and entry schemas. 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. useAppState picks the store by it.
keystring
The key passed as the first argument.
urlUrl
The url schema as passed. Hand it to a page’s search export in @k8ordo/framework’s server mode, or to @k8ordo/form’s formFields.
entryEntry
The entry schema as passed.
parseUrl(input: UrlInput) => OutputOf<Url>
Reads the url values. 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 base is prepended.
search(values?) => string
Returns the query string alone, without the ?.

Caveats

  • Every field needs .default() or .optional(). Without one, the module throws fields must tolerate absence as it loads.
  • A url boolean is z.stringbool() and a url array defaults to []. Any other spelling throws as the module loads.
  • A field declared in both url and entry is a type error, and throws declares in both url and entry at runtime. Passing neither throws declares neither url nor entry.
src/state.ts
export 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.

ts
urlReader<Url extends StateSchema>(
  schema: Url,
): (input: UrlInput) => output<Url>

Parameters

schemaStateSchema
A url schema.

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 exports search through it.

defineLocalState

Import from @k8ordo/state

Defines state in localStorage. It stays until deleted and is shared by every tab on the device.

ts
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 version and migrate for 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. useAppState picks 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 or null. Neither the schema nor migrate runs.

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 storage event.

defineSessionState

Import from @k8ordo/state

Defines state in sessionStorage. It survives a reload and goes with the tab.

ts
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. useAppState picks 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 or null. The schema does not run.

Caveats

  • It takes no version or migrate.
  • A defineLocalState with the same key is a different state.

Import from @k8ordo/state

Defines state in a cookie. The browser writes it, and every request carries it to the server.

ts
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 cookie as the module loads.
schemaStateSchema
The schema of the stored values. Its fields follow the same rules as definePageState’s caveats.
versioningVersioning
The version and migrate for 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. useAppState picks 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 Map of percent-decoded values. In @k8ordo/framework’s server mode, pass request.cookies as 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=Lax and a Max-Age of 400 days. The API always adds Secure.
  • 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.

ts
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. useAppState picks 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. Each update() 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.

ts
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. initialUrl is accepted only by a page state with url, initialCookie only by a cookie state.

Returns

[state, update] — The current values, and the function that changes them.

Caveats

  • A page state’s values are its url and entry merged into one object.
  • The server render and the hydration render show the defaults. With initialUrl or initialCookie they show those values, and a memory state shows its initial values.
  • update(patch, options?) applies on the spot and returns an UpdateHandle. Except for memory state, the calls made in one handler go out as one write. options exists only on page state.
  • No Provider is needed. The store is created on first use.
pager.tsx
const [{ 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.

ts
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().

ts
type UpdateOptions = {
  history?: 'push' | 'replace';
};

Fields

history'push' | 'replace'
'replace' by default. 'push' adds a history entry, and only when a url value changes.

Caveats

  • No other kind’s update() takes this argument.

Versioning

Import from @k8ordo/state

The third argument of defineLocalState and defineCookieState.

ts
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. fromVersion is the version the value was written with, 0 for 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 migrate that 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.

ts
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. routes wins 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>: Path when accepted, never when 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.

ts
resetStateRegistry(): void

Caveats

  • Unmount components first.
  • Stored values stay. Delete them by storageKey or cookieName.

OutputOf

Import from @k8ordo/state

A schema’s output type. Use it to type the props that carry initialUrl or initialCookie.

ts
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 is undefined, 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.

ts
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.

ts
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.

ts
type AnyState =
  | PageState
  | LocalState
  | SessionState
  | CookieState
  | MemoryState;
k8ordo

React libraries that use Baseline features without holding back.