/
[index].tsx
executable file
·250 lines (237 loc) · 6.94 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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
import { memo, useEffect, useRef } from 'react'
import type { GetServerSideProps, NextPage } from 'next'
import Head from 'next/head'
import Router from 'next/router'
import { SubmitHandler } from 'react-hook-form/dist/types/form'
import { syncEffect } from 'recoil-sync'
import { array, object, string } from '@recoiljs/refine'
import { initializableAtomFamily } from 'recoil-sync-next'
import { Links } from '../../src/components/Links'
import { useFormSync } from '../../src/hooks/useFormSync'
import styles from '../../styles/form.module.css'
type FormState = {
name: string
comment: string
time: string
selectedRadio: string
selectedCheckbox: readonly string[]
items: readonly {
radio: string
checkbox: string
text: string
}[]
}
const formState = initializableAtomFamily<FormState, string>({
key: 'urlFormState',
effects: [
syncEffect({
storeKey: 'url-store',
refine: object({
name: string(),
comment: string(),
time: string(),
selectedRadio: string(),
selectedCheckbox: array(string()),
items: array(
object({
radio: string(),
checkbox: string(),
text: string(),
})
),
}),
}),
],
})
type PageProps = {
index: string
defaultValues: FormState
}
let count = 1
const createNewItem = (): FormState['items'][number] => ({
radio: `${count}`,
checkbox: `${count++}`,
text: '',
})
const URLForm: NextPage<PageProps> = ({ index, defaultValues }) => {
// check render
const renderRef = useRef(true)
if (renderRef.current) {
renderRef.current = false
console.log(`URLForm[${index}]: initial render`)
} else {
console.log(`URLForm[${index}]: re render`)
}
const {
control,
registerWithDefaultValue,
registerWithDefaultChecked,
onChangeForm,
handleSubmit,
reset,
resetFormOnly,
useFieldArraySync,
} = useFormSync<FormState>(formState(index, defaultValues))
const { fields, append, prepend, remove, swap, move, insert } =
useFieldArraySync({
control,
name: 'items',
})
/*
* Next.js dynamic routes does not unmount page components
* when only slugs are changed (just re-rendering).
* Therefore, uncontrolled input elements are not updated
* from the previous page (i.e. slug).
* To solve this problem, when slugs ('index' in this case) change,
* reset the RHF form state to reflect the Recoil state.
* Unlike reset(), resetFormOnly() doesn't reset the Recoil state.
*/
useEffect(() => {
resetFormOnly()
}, [index, resetFormOnly])
const onSubmit: SubmitHandler<FormState> = async (data) => {
console.log('submit data', data)
await Router.push('/success')
}
return (
<div className={styles.container}>
<Head>
<title>URLForm[{index}]</title>
<link rel="icon" href="/favicon.ico" />
</Head>
<main className={styles.main}>
<h1 className={styles.title}>URLForm[{index}]</h1>
<form onSubmit={handleSubmit(onSubmit)} onChange={onChangeForm}>
<dl className={styles.formList}>
<dt>name</dt>
<dd>
<input type="text" {...registerWithDefaultValue('name')} />
</dd>
<dt>comment</dt>
<dd>
<input type="text" {...registerWithDefaultValue('comment')} />
</dd>
<dt>time</dt>
<dd>
<input type="text" {...registerWithDefaultValue('time')} />
</dd>
<dt>items</dt>
<dd>
<button type="button" onClick={() => prepend(createNewItem())}>
Prepend
</button>
<ul>
{fields.map((field, index) => (
<li key={field.id}>
<span>{index} </span>
<input
type="radio"
{...registerWithDefaultChecked(
'selectedRadio',
field.radio
)}
/>
<input
type="checkbox"
{...registerWithDefaultChecked(
'selectedCheckbox',
field.checkbox
)}
/>
<input
{...registerWithDefaultValue(
`items.${index}.text` as const
)}
/>
<button
type="button"
onClick={() => insert(index, createNewItem())}
>
Insert before
</button>
<button
type="button"
onClick={() => insert(index + 1, createNewItem())}
>
Insert after
</button>
<button
type="button"
disabled={index >= fields.length - 1}
onClick={() => swap(index, index + 1)}
>
Swap to next
</button>
<button type="button" onClick={() => move(index, 0)}>
Move to first
</button>
<button type="button" onClick={() => remove(index)}>
Remove
</button>
</li>
))}
</ul>
<button type="button" onClick={() => append(createNewItem())}>
Append
</button>
</dd>
</dl>
<div>
<button>Submit</button>
</div>
<div>
<button type="button" onClick={() => reset()}>
Reset (to Default Values)
</button>
<button
type="button"
onClick={() =>
reset({
name: '',
comment: '',
time: '',
selectedRadio: '',
selectedCheckbox: [],
items: [],
})
}
>
Reset (to Empty Values)
</button>
</div>
</form>
<Links />
</main>
</div>
)
}
export default memo(URLForm)
export const getServerSideProps: GetServerSideProps<PageProps> = async ({
params,
}) => {
console.log(`URLForm[${params?.index}]: executing gSSP`)
return {
props: {
index: params?.index as string,
defaultValues: {
name: 'a',
comment: 'b',
time: new Date().toLocaleTimeString(),
selectedRadio: 'A',
selectedCheckbox: ['A'],
items: [
{
radio: 'A',
checkbox: 'A',
text: '',
},
{
radio: 'B',
checkbox: 'B',
text: '',
},
],
},
},
}
}