101 lines
2.6 KiB
TypeScript
101 lines
2.6 KiB
TypeScript
"use client";
|
|
|
|
import { zodResolver } from "@hookform/resolvers/zod";
|
|
import { useForm } from "react-hook-form";
|
|
import { z } from "zod";
|
|
import { Button } from "@/components/ui/button";
|
|
import {
|
|
Form,
|
|
FormControl,
|
|
FormField,
|
|
FormItem,
|
|
FormMessage,
|
|
} from "@/components/ui/form";
|
|
|
|
const formSchema = z.object({
|
|
username: z.string().min(2, {
|
|
message: "Username must be at least 2 characters.",
|
|
}),
|
|
});
|
|
|
|
import React from "react";
|
|
import { Input } from "@/components/ui/input";
|
|
import { groupSchema } from "@/lib/validations/group";
|
|
import { api } from "@/trpc/react";
|
|
import { useRouter } from "next/navigation";
|
|
import type { Group } from "@/server/db/schema";
|
|
import { Textarea } from "@/components/ui/textarea";
|
|
|
|
function GroupForm({ initialGroup }: { initialGroup?: Group }) {
|
|
const router = useRouter();
|
|
const utils = api.useUtils();
|
|
const createGroup = api.group.create.useMutation({
|
|
onSuccess(group) {
|
|
router.push(`/group/${group?.id}`);
|
|
utils.invalidate();
|
|
},
|
|
});
|
|
const updateGroup = api.group.update.useMutation({
|
|
onSuccess() {
|
|
utils.group.get.invalidate({ id: initialGroup?.id });
|
|
},
|
|
});
|
|
const form = useForm<z.infer<typeof groupSchema>>({
|
|
resolver: zodResolver(groupSchema),
|
|
defaultValues: {
|
|
name: initialGroup?.name ?? "",
|
|
description: initialGroup?.description ?? "",
|
|
},
|
|
});
|
|
|
|
const existing = Boolean(initialGroup?.id?.length);
|
|
|
|
function onSubmit(group: z.infer<typeof groupSchema>) {
|
|
if (existing) {
|
|
updateGroup.mutate({ group, groupId: initialGroup?.id! });
|
|
} else {
|
|
createGroup.mutate({ group });
|
|
}
|
|
}
|
|
|
|
return (
|
|
<Form {...form}>
|
|
<form onSubmit={form.handleSubmit(onSubmit)} className="space-y-8">
|
|
<FormField
|
|
control={form.control}
|
|
name="name"
|
|
render={({ field }) => (
|
|
<FormItem>
|
|
<FormControl>
|
|
<Input
|
|
autoFocus={!existing}
|
|
placeholder="What is your groups name?"
|
|
{...field}
|
|
/>
|
|
</FormControl>
|
|
<FormMessage />
|
|
</FormItem>
|
|
)}
|
|
/>
|
|
<FormField
|
|
control={form.control}
|
|
name="description"
|
|
render={({ field }) => (
|
|
<FormItem>
|
|
<FormControl>
|
|
<Textarea placeholder="What is your groups name?" {...field} />
|
|
</FormControl>
|
|
<FormMessage />
|
|
</FormItem>
|
|
)}
|
|
/>
|
|
<Button type="submit" className="w-full">
|
|
{existing ? "Update" : "Create"} Group
|
|
</Button>
|
|
</form>
|
|
</Form>
|
|
);
|
|
}
|
|
|
|
export default GroupForm;
|