ilokesto

validate

validate runs a Standard Schema v1 validator before the store accepts the next state. If validation fails, the update is stopped and an error is logged.

Signature

validate<T>(initialState: T | Store<T>, schema: StandardSchemaV1<T, T>): Store<T>
validate<T>(schema: StandardSchemaV1<T, T>): (initialState: T | Store<T>) => Store<T>

Example

import { validate } from '@ilokesto/state/middleware';

type CounterState = { count: number };

const schema = {
  '~standard': {
    version: 1,
    vendor: 'counter',
    validate(value: unknown) {
      if (typeof value === 'object' && value !== null && typeof (value as CounterState).count === 'number') {
        return { value: value as CounterState };
      }
      return { issues: [{ message: 'count must be a number' }] };
    },
  },
} as const;

const store = validate({ count: 0 }, schema);

What happens on failure

When the schema returns issues, validate logs [Validation Error] Invalid state: and does not call the next middleware. The store keeps its previous state.

Async caveat

Async Standard Schema validation is not supported. If validate() returns a Promise-like result, the middleware logs an async validation error and stops the update. Run async checks before calling setState.

On this page