Created
February 17, 2025 19:22
-
-
Save mmikhan/4c133524f75e4f3bf6b40f3ab747627a to your computer and use it in GitHub Desktop.
An example of Zod schema together with a React client component to submit an array of object through the input form
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
export const WEBHOOK_CONFIG_MODES = [ | |
{ value: "auto", label: "Auto" }, | |
{ value: "manual", label: "Manual" }, | |
] as const; | |
export type WebhookConfigMode = (typeof WEBHOOK_CONFIG_MODES)[number]; | |
export const WEBHOOK_CONFIG_MODE_VALUES = WEBHOOK_CONFIG_MODES.map( | |
(mode) => mode.value, | |
) as [string, ...string[]]; | |
export const webhookForPaymentProviderSchema = z.object({ | |
mode: z | |
.array( | |
z.object({ | |
value: z.enum(WEBHOOK_CONFIG_MODE_VALUES), | |
label: z.string(), | |
}), | |
) | |
.default([{ value: "auto", label: "Auto" }]), | |
}) |
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
'use client' | |
export default function WebhookForm() { | |
const form = useForm<WebhookForPaymentProvider>({ | |
resolver: zodResolver(webhookForPaymentProviderSchema), | |
}); | |
async function onSubmit(formData: WebhookForPaymentProvider) { | |
console.log("formData", formData); | |
} | |
return ( | |
<Form {...form}> | |
<form onSubmit={form.handleSubmit(onSubmit)} className="space-y-3"> | |
<FormField | |
control={form.control} | |
name="mode" | |
render={({ field }) => ( | |
<FormItem> | |
<FormLabel>Configuration</FormLabel> | |
<Select | |
{/* Here is the magic */} | |
onValueChange={(value) => { | |
const mode = WEBHOOK_CONFIG_MODES.find( | |
(m) => m.value === value, | |
); | |
field.onChange([{ value, label: mode?.label ?? "" }]); | |
}} | |
value={field.value?.[0]?.value} | |
> | |
<FormControl> | |
<SelectTrigger> | |
<SelectValue placeholder="Select webhook configuration mode" /> | |
</SelectTrigger> | |
</FormControl> | |
<SelectContent> | |
{WEBHOOK_CONFIG_MODES.map((mode, i) => ( | |
<SelectItem key={i} value={mode.value}> | |
{mode.label} | |
</SelectItem> | |
))} | |
</SelectContent> | |
</Select> | |
<FormDescription> | |
Choose whether to configure webhooks automatically or | |
manually. | |
</FormDescription> | |
<FormMessage /> | |
</FormItem> | |
)} | |
/> | |
</form | |
</Form> | |
) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Submitting the form will output an object like the following: