-
-
Notifications
You must be signed in to change notification settings - Fork 625
Expand file tree
/
Copy pathclient-component.tsx
More file actions
62 lines (57 loc) · 1.54 KB
/
client-component.tsx
File metadata and controls
62 lines (57 loc) · 1.54 KB
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
55
56
57
58
59
60
61
62
'use client'
import { useActionState, useCallback } from 'react'
import {
initialFormState,
mergeForm,
useForm,
useTransform,
} from '@tanstack/react-form-nextjs'
import { z } from 'zod'
import someAction from './action'
import { formOpts } from './shared-code'
export const ClientComp = () => {
const [state, action] = useActionState(someAction, initialFormState)
// debugger
const form = useForm({
...formOpts,
transform: useCallback(
(baseForm: unknown) => mergeForm(baseForm as never, state ?? {}),
[state],
),
})
return (
<form action={action as never} onSubmit={() => form.handleSubmit()}>
<form.Field
name="age"
validators={{
onChange: z.coerce.number().min(8),
}}
>
{(field) => {
return (
<div>
<input
name="age"
type="number"
value={field.state.value}
onChange={(e) => field.handleChange(e.target.valueAsNumber)}
/>
{field.state.meta.errors.map((error) => (
<p key={error?.message ?? ''}>{error?.message}</p>
))}
</div>
)
}}
</form.Field>
<form.Subscribe
selector={(formState) => [formState.canSubmit, formState.isSubmitting]}
>
{([canSubmit, isSubmitting]) => (
<button type="submit" disabled={!canSubmit}>
{isSubmitting ? '...' : 'Submit'}
</button>
)}
</form.Subscribe>
</form>
)
}