diff --git a/app/forms/GroupForm.tsx b/app/forms/GroupForm.tsx index 8d41cf6..d224e85 100644 --- a/app/forms/GroupForm.tsx +++ b/app/forms/GroupForm.tsx @@ -1,10 +1,11 @@ import { MemberRole, type Prisma } from '@prisma/client' import type { ActionFunctionArgs } from '@remix-run/node' import { redirect } from '@remix-run/node' +import { useActionData } from '@remix-run/react' import { withZod } from '@remix-validated-form/with-zod' import { ValidatedForm, validationError } from 'remix-validated-form' import { z } from 'zod' -import { H3 } from '~/components/typography' +import { ErrorMessage, H3 } from '~/components/typography' import { Button } from '~/components/ui/button' import { FormInput } from '~/components/ui/form' import { routes } from '~/routes' @@ -15,14 +16,32 @@ let groupSchema = z.object({ name: z.string(), }) satisfies z.ZodType -let groupValidator = withZod(groupSchema) +let clientGroupValidator = withZod(groupSchema) export async function submitGroupForm({ request, id, }: ActionFunctionArgs & { id?: string }) { + let serverGroupValidator = withZod( + groupSchema.refine( + async ({ name }) => { + let existingGroup = await db.group.findFirst({ + where: { + name, + }, + }) + + return !existingGroup + }, + { + message: 'A group with this name already exists', + path: ['name'], + }, + ), + ) + let user = await requireAuthentication(request) - let form = await groupValidator.validate(await request.formData()) + let form = await serverGroupValidator.validate(await request.formData()) if (form.error) { return validationError(form.error) @@ -77,17 +96,22 @@ export function GroupForm({ }: { defaultValues?: z.infer }) { + let data = useActionData() + return (

Create Group

+ {data?.fieldErrors.name && ( + {data.fieldErrors.name} + )}
diff --git a/app/routes/app.groups.create.tsx b/app/routes/app.groups.create.tsx index 2ab637a..b501ac1 100644 --- a/app/routes/app.groups.create.tsx +++ b/app/routes/app.groups.create.tsx @@ -1,15 +1,11 @@ import type { ActionFunctionArgs } from '@remix-run/node' -import { redirect } from '@remix-run/node' import { GroupForm, submitGroupForm } from '~/forms/GroupForm' -import { routes } from '~/routes' import { requireAuthentication } from '~/services/auth.server' export async function action(args: ActionFunctionArgs) { await requireAuthentication(args.request) - await submitGroupForm(args) - - return redirect(routes.groups()) + return await submitGroupForm(args) } export default function CreateGroupPage() {