Created
August 30, 2022 09:10
-
-
Save nitaking/2658d7726120feadf7defaef8ca35f07 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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