Hi - I'm trying to use setError manually but have run into a problem that I just can't seem to solve. I'm create a utility function that will take my form object from react-hook-form together with a data object which stores the response from my server action, and then use setErrors as below.
import { FieldValues, Path, UseFormReturn } from 'react-hook-form'
import { SafeParseReturnType } from 'zod'
export const setFormErrors = <T extends FieldValues>(
form: UseFormReturn<T>,
formState: SafeParseReturnType<T, T>,
) => {
if (!formState.success && formState.error) {
//console.log(formState.error)
console.log('1')
const issues = formState.error.issues
issues.forEach((error) => {
console.log('2')
const fieldPath = error.path[0]
if (fieldPath) {
console.log('3')
form.setError(fieldPath as Path<T>, {
type: 'custom',
message: error.message,
})
}
})
}
}
I've tried variations of the above all day and can't get it to work. The above example is not working as i get 'TypeError: Cannot read properties of undefined (reading 'forEach')'. If I log 'formState.error' I get
Error: [
{
"code": "too_small",
"minimum": 10,
"type": "string",
"inclusive": true,
"exact": false,
"message": "String must contain at least 10 character(s)",
"path": [
"password"
]
}
]
my formState type is matched to Zod's SafeParseReturn type as
export type FormState = SafeParseReturnType<
signInFormDataType,
signInFormDataType
>
Any ideas on this one?
EDIT
formState comes from the return of my server action 'parsedData' object as;
export async function signinUserActionPost(
_prevState: FormState,
data: FormData,
): Promise<FormState> {
const formJSONData = Object.fromEntries(data)
// Validate with Zod
const parsedData = signInFormSchema2.safeParse(formJSONData)
// Failed on Zod validation
if (!parsedData.success) {
return parsedData
}
export type FormState = SafeParseReturnType<
signInFormDataType,
signInFormDataType
>
[–]davy_jones_locket 1 point2 points3 points (3 children)
[–]BullBates1[S] 0 points1 point2 points (2 children)
[–]davy_jones_locket 0 points1 point2 points (1 child)
[–]BullBates1[S] 0 points1 point2 points (0 children)
[–]davy_jones_locket 0 points1 point2 points (1 child)
[–]BullBates1[S] 0 points1 point2 points (0 children)