Skip to content

Instantly share code, notes, and snippets.

@mmikhan
Created February 17, 2025 19:22
Show Gist options
  • Save mmikhan/4c133524f75e4f3bf6b40f3ab747627a to your computer and use it in GitHub Desktop.
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
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" }]),
})
'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>
)
}
@mmikhan
Copy link
Author

mmikhan commented Feb 17, 2025

Submitting the form will output an object like the following:

{
mode: [
    {
        "value": "manual",
        "label": "Manual"
    }
  ]
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment