valibot: Add an example for handling ValiError errors
I would like to see how to correctly handle the ValiError when parsing a schema. In a type-safe manner. For example in this login form handling demo:
const LoginSchema = v.object({
email: v.pipe(v.string(), v.nonEmpty(), v.email() ),
password: v.pipe(v.string(), v.nonEmpty(), v.minLength(6) ),
});
const [formData, setFormData] = useState<LoginSchemaType>({
email: '',
password: '',
});
const [formErrors, setFormErrors] = useState<`What HERE?`>();
const handleLogin = async () => {
setFormErrors({});
try {
v.parse(LoginSchema, formData)
await loginMutation(formData)
} catch (error) {
if (error instanceof v.ValiError && error.issues) {
const flatIssues = v.flatten<typeof LoginSchema>(error?.issues)
const newErrors = {};
Object.entries(flatIssues.nested).forEach(([key, value]) => {
newErrors[key] = value[0]
})
setFormErrors(newErrors);
} else {
console.error(error)
}
}
};
I am getting a crazy type issue on Object.entries(flatIssues.nested) at this point.
More importantly, how to type the formErrors variables?
I would love to see the team’s approach to this.
About this issue
- Original URL
- State: closed
- Created 2 years ago
- Comments: 15 (7 by maintainers)
Okay, I ended up doing something like this. And it works well enough.
I hope this could be useful to someone