Skip to content

Instantly share code, notes, and snippets.

@nitaking
Created August 30, 2022 09:10
Show Gist options
  • Save nitaking/2658d7726120feadf7defaef8ca35f07 to your computer and use it in GitHub Desktop.
Save nitaking/2658d7726120feadf7defaef8ca35f07 to your computer and use it in GitHub Desktop.
const UserScheme = z.object({
name: z.string().nonempty().max(50),
age: z.number().min(1).max(200),
});
type Values = z.infer<typeof UserScheme>;
type Forms = {
setName: (value: string) => void;
setAge: (value: number) => void;
valid: boolean;
invalid: boolean;
};
export const useForm = (): [Values, Forms] => {
const [name, setName] = useState('');
const [age, setAge] = useState(12);
const validation = useCallback(
() =>
UserScheme.safeParse({
name,
age,
}).success,
[age, name],
);
const valid = useMemo(() => validation(), [validation]);
const invalid = useMemo(() => !valid, [valid]);
return [
{
name,
age,
},
{
setName,
setAge,
valid,
invalid,
},
];
};
...
const Component = () => {
const [values, form] = useForm()
return (
<Button disabled={form.invalid} ... />
)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment