-
Notifications
You must be signed in to change notification settings - Fork 85
/
_index.tsx
54 lines (47 loc) · 1.51 KB
/
_index.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
import { getFormProps, getInputProps, useForm } from '@conform-to/react';
import { parseWithZod } from '@conform-to/zod';
import type { ActionFunctionArgs, LoaderFunctionArgs } from '@remix-run/node';
import { json } from '@remix-run/node';
import { Form, useActionData, useLoaderData } from '@remix-run/react';
import { z } from 'zod';
import { Playground, Field } from '~/components';
const schema = z.object({
name: z.string({ required_error: 'Name is required' }),
});
export async function loader({ request }: LoaderFunctionArgs) {
const url = new URL(request.url);
return {
noClientValidate: url.searchParams.get('noClientValidate') === 'yes',
};
}
export async function action({ request }: ActionFunctionArgs) {
const formData = await request.formData();
const submission = parseWithZod(formData, { schema });
return json(
submission.reply({
fieldErrors: {
name: ['Something went wrong'],
},
}),
);
}
export default function Example() {
const { noClientValidate } = useLoaderData<typeof loader>();
const lastResult = useActionData<typeof action>();
const [form, fields] = useForm({
lastResult,
shouldValidate: 'onBlur',
onValidate: !noClientValidate
? ({ formData }) => parseWithZod(formData, { schema })
: undefined,
});
return (
<Form method="post" {...getFormProps(form)}>
<Playground title="Template Form" result={lastResult}>
<Field label="Name" meta={fields.name}>
<input {...getInputProps(fields.name, { type: 'text' })} />
</Field>
</Playground>
</Form>
);
}