Discriminated union + useFieldArray + error messages #13044
-
I'm trying to access the error messages per field but since i'm using a descriminated union i'm having a tough time narrowing it. const formSchema = z.object({
editChanges: z.array(
z.discriminatedUnion("action", [
z.object({
id: z.number(),
action: z.literal(EditActions.DELETE_GROUP),
data: z.object({
id: z.number(),
groupName: z.string(),
}),
}),
z.object({
id: z.number(),
action: z.literal(EditActions.RENAME_GROUP),
data: z
.object({
id: z.number(),
oldGroupName: z.string(),
newGroupName: z.string(),
})
.superRefine((data, ctx) => {
const newName = data.newGroupName.trim();
const oldName = data.oldGroupName.trim();
if (oldName === newName) {
ctx.addIssue({
code: "custom",
message: "Group name cannot be the same",
path: ["newGroupName"],
});
}
}),
}),
])
),
}); When i try to get the error messages i'm not getting the correct shape on data because I have no way to descriminate against 'action'
Any help/hint is appreciated. Repro is here https://codesandbox.io/p/sandbox/f8rn68 |
Beta Was this translation helpful? Give feedback.
Answered by
BrendanC23
Sep 3, 2025
Replies: 1 comment 1 reply
-
How about this? See the CodeSandbox. const errorData = errors.editChanges?.[index]?.data;
console.log(errorData);
const errorMessage =
errorData && "newGroupName" in errorData
? errorData.newGroupName?.message
: false; |
Beta Was this translation helpful? Give feedback.
1 reply
Answer selected by
meckanism
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
How about this? See the CodeSandbox.