Skip to Content
Middlewaresvalidate

validate

The validate middleware is a useful tool for enhancing type safety in state management. This middleware validates data against a predefined schema before the state is changed. This helps maintain state consistency and stability by preventing invalid data from being reflected in the application state. If an invalid state change attempt occurs, the change is blocked, and detailed error information is immediately printed to the console, facilitating debugging.

const useStore = create( validate(initialState, Resolver<T>) )

The validate middleware in caro-kann internally utilizes common-resolver, allowing for easy integration with various widely used validation libraries such as zod, yup, and superstruct. This offers the advantage that developers can effectively manage the integrity of state data using familiar tools or those already implemented in their projects.

import { z } from "zod"; import * as yup from "yup"; import { object, number } from "superstruct"; import { zodResolver } from "common-resolver/zod" import { yupResolver } from "common-resolver/yupResolver" import { superstructResolver } from "common-resolver/superstructResolver" const zSchema = z.object({ count: z.number().min(0) }); const ySchema = yup.object({ count: yup.number().min(0).required() }); const sSchema = object({ count: number() }); const useStore = create( validate({ count: 0 }, zodResolver(zSchema)) // validate({ count: 0 }, yupResolver(ySchema)) // validate({ count: 0 }, superstructResolver(sSchema)) ); export default function Page() { const [count, setCount] = useStore(store => store.count) return ( <div> <h1>{count}</h1> <button onClick={() => setCount(count => count + 1)}>Increment</button> <button onClick={() => setCount(count => count - 1)}>Decrement</button> </div> ) }
Last updated on