Open History to see the last commit
1/* eslint-disable react-compiler/react-compiler */
2import { describe, expect, it, vi } from 'vitest'
3import { render, waitFor } from '@testing-library/react'
4import { userEvent } from '@testing-library/user-event'
5import { StrictMode, useState } from 'react'
6import { useStore } from '@tanstack/react-store'
7import { useForm } from '../src/index'
8import { sleep } from './utils'
9import type { AnyFieldApi } from '../src/index'
10β
11const user = userEvent.setup()
12β
13describe('useField', () => {
14 it('should allow to set default value', () => {
15 type Person = {
16 firstName: string
17 lastName: string
18 }
19β
20 function Comp() {
21 const form = useForm({
22 defaultValues: {
23 firstName: 'FirstName',
24 lastName: 'LastName',
25 } as Person,
26 })
27β
28 return (
29 <>
30 <form.Field
31 name="firstName"
32 children={(field) => {
33 return (
34 <input
35 data-testid="fieldinput"
36 value={field.state.value}
37 onBlur={field.handleBlur}
38 onChange={(e) => field.handleChange(e.target.value)}
39 />
40 )
41 }}
42 />
43 </>
44 )
45 }
46β
47 const { getByTestId } = render(<Comp />)
48 const input = getByTestId('fieldinput')
49 expect(input).toHaveValue('FirstName')
50 })
51β
52 it('should use field default value first', () => {
53 type Person = {
54 firstName: string
55 lastName: string
56 }
57β
58 function Comp() {
59 const form = useForm({
60 defaultValues: {
61 firstName: 'FirstName',
62 lastName: 'LastName',
63 } as Person,
64 })
65β
66 return (
67 <>
68 <form.Field
69 name="firstName"
70 defaultValue="otherName"
71 children={(field) => {
72 return (
73 <input
74 data-testid="fieldinput"
75 value={field.state.value}
76 onBlur={field.handleBlur}
77 onChange={(e) => field.handleChange(e.target.value)}
78 />
79 )
80 }}
81 />
82 </>
83 )
84 }
85β
86 const { getByTestId } = render(<Comp />)
87 const input = getByTestId('fieldinput')
88 expect(input).toHaveValue('otherName')
89 })
90β
91 it('should not validate on change if isTouched is false', async () => {
92 type Person = {
93 firstName: string
94 lastName: string
95 }
96 const error = 'Please enter a different value'
97β
98 function Comp() {
99 const form = useForm({
100 defaultValues: {
101 firstName: '',
102 lastName: '',
103 } as Person,
104 })
105β
106 return (
107 <>
108 <form.Field
109 name="firstName"
110 validators={{
111 onChange: ({ value }) => (value === 'other' ? error : undefined),
112 }}
113 children={(field) => (
114 <div>
115 <input
116 data-testid="fieldinput"
117 name={field.name}
118 value={field.state.value}
119 onBlur={field.handleBlur}
120 onChange={(e) =>
121 field.setValue(e.target.value, {
122 dontUpdateMeta: true,
123 })
124 }
125 />
126 <p>{field.getMeta().errors}</p>
127 </div>
128 )}
129 />
130 </>
131 )
132 }
133β
134 const { getByTestId, queryByText } = render(<Comp />)
135 const input = getByTestId('fieldinput')
136 await user.type(input, 'other')
137 expect(queryByText(error)).not.toBeInTheDocument()
138 })
139β
140 it('should validate on change if isTouched is true', async () => {
141 type Person = {
142 firstName: string
143 lastName: string
144 }
145 const error = 'Please enter a different value'
146β
147 function Comp() {
148 const form = useForm({
149 defaultValues: {
150 firstName: '',
151 lastName: '',
152 } as Person,
153 })
154β
155 return (
156 <>
157 <form.Field
158 name="firstName"
159 defaultMeta={{ isTouched: true }}
160 validators={{
161 onChange: ({ value }) => (value === 'other' ? error : undefined),
162 }}
163 children={(field) => (
164 <div>
165 <input
166 data-testid="fieldinput"
167 name={field.name}
168 value={field.state.value}
169 onBlur={field.handleBlur}
170 onChange={(e) => field.handleChange(e.target.value)}
171 />
172 <p>{field.getMeta().errorMap.onChange}</p>
173 </div>
174 )}
175 />
176 </>
177 )
178 }
179β
180 const { getByTestId, getByText, queryByText } = render(<Comp />)
181 const input = getByTestId('fieldinput')
182 expect(queryByText(error)).not.toBeInTheDocument()
183 await user.type(input, 'other')
184 expect(getByText(error)).toBeInTheDocument()
185 })
186β
187 it('should validate on change and on blur', async () => {
188 type Person = {
189 firstName: string
190 lastName: string
191 }
192 const onChangeError = 'Please enter a different value (onChangeError)'
193 const onBlurError = 'Please enter a different value (onBlurError)'
194β
195 function Comp() {
196 const form = useForm({
197 defaultValues: {
198 firstName: '',
199 lastName: '',
200 } as Person,
201 })
202β
203 return (
204 <>
205 <form.Field
206 name="firstName"
207 defaultMeta={{ isTouched: true }}
208 validators={{
209 onChange: ({ value }) =>
210 value === 'other' ? onChangeError : undefined,
211 onBlur: ({ value }) =>
212 value === 'other' ? onBlurError : undefined,
213 }}
214 children={(field) => (
215 <div>
216 <input
217 data-testid="fieldinput"
218 name={field.name}
219 value={field.state.value}
220 onBlur={field.handleBlur}
221 onChange={(e) => field.handleChange(e.target.value)}
222 />
223 <p>{field.getMeta().errorMap.onChange}</p>
224 <p>{field.getMeta().errorMap.onBlur}</p>
225 </div>
226 )}
227 />
228 </>
229 )
230 }
231β
232 const { getByTestId, getByText, queryByText } = render(<Comp />)
233 const input = getByTestId('fieldinput')
234 expect(queryByText(onChangeError)).not.toBeInTheDocument()
235 expect(queryByText(onBlurError)).not.toBeInTheDocument()
236 await user.type(input, 'other')
237 expect(getByText(onChangeError)).toBeInTheDocument()
238 await user.click(document.body)
239 expect(queryByText(onBlurError)).toBeInTheDocument()
240 })
241β
242 it('should properly update conditionally rendered fields', async () => {
243 type FormValues = {
244 firstField: string
245 secondField: string
246 showFirstField: boolean
247 }
248β
249 function Comp() {
250 const form = useForm({
251 defaultValues: {
252 firstField: '',
253 secondField: '',
254 showFirstField: true,
255 } as FormValues,
256 })
257β
258 return (
259 <>
260 <form.Field name="showFirstField">
261 {({ handleChange, state }) => (
262 <div>
263 <span>Show first field</span>
264 <input
265 data-testid="show-first-field"
266 checked={state.value}
267 type="checkbox"
268 onChange={(e) => {
269 handleChange(e.target.checked)
270 }}
271 />
272 </div>
273 )}
274 </form.Field>
275 <form.Subscribe selector={(state) => state.values.showFirstField}>
276 {(someFlagChecked) => {
277 if (someFlagChecked) {
278 return (
279 <form.Field name="firstField">
280 {({ handleChange, state }) => (
281 <label>
282 first field
283 <input
284 data-testid="first-field"
285 value={state.value}
286 onChange={(e) => handleChange(e.target.value)}
287 />
288 </label>
289 )}
290 </form.Field>
291 )
292 }
293β
294 return (
295 <form.Field name="secondField">
296 {({ handleChange, state }) => (
297 <label>
298 second field
299 <input
300 data-testid="second-field"
301 value={state.value}
302 onChange={(e) => handleChange(e.target.value)}
303 />
304 </label>
305 )}
306 </form.Field>
307 )
308 }}
309 </form.Subscribe>
310 </>
311 )
312 }
313β
314 const { getByTestId } = render(<Comp />)
315β
316 const showFirstFieldInput = getByTestId('show-first-field')
317β
318 await user.type(getByTestId('first-field'), 'hello')
319 expect((getByTestId('first-field') as HTMLInputElement).value).toBe('hello')
320β
321 await user.click(showFirstFieldInput)
322 await user.type(getByTestId('second-field'), 'world')
323 expect((getByTestId('second-field') as HTMLInputElement).value).toBe(
324 'world',
325 )
326β
327 await user.click(showFirstFieldInput)
328 expect((getByTestId('first-field') as HTMLInputElement).value).toBe('hello')
329 })
330β
331 it('should validate async on change', async () => {
332 type Person = {
333 firstName: string
334 lastName: string
335 }
336 const error = 'Please enter a different value'
337β
338 function Comp() {
339 const form = useForm({
340 defaultValues: {
341 firstName: '',
342 lastName: '',
343 } as Person,
344 })
345β
346 return (
347 <>
348 <form.Field
349 name="firstName"
350 defaultMeta={{ isTouched: true }}
351 validators={{
352 onChangeAsync: async () => {
353 await sleep(10)
354 return error
355 },
356 }}
357 children={(field) => (
358 <div>
359 <input
360 data-testid="fieldinput"
361 name={field.name}
362 value={field.state.value}
363 onBlur={field.handleBlur}
364 onChange={(e) => field.handleChange(e.target.value)}
365 />
366 <p>{field.getMeta().errorMap.onChange}</p>
367 </div>
368 )}
369 />
370 </>
371 )
372 }
373β
374 const { getByTestId, getByText, queryByText } = render(<Comp />)
375 const input = getByTestId('fieldinput')
376 expect(queryByText(error)).not.toBeInTheDocument()
377 await user.type(input, 'other')
378 await waitFor(() => getByText(error))
379 expect(getByText(error)).toBeInTheDocument()
380 })
381β
382 it('should validate async on change and async on blur', async () => {
383 type Person = {
384 firstName: string
385 lastName: string
386 }
387 const onChangeError = 'Please enter a different value (onChangeError)'
388 const onBlurError = 'Please enter a different value (onBlurError)'
389β
390 function Comp() {
391 const form = useForm({
392 defaultValues: {
393 firstName: '',
394 lastName: '',
395 } as Person,
396 })
397β
398 return (
399 <>
400 <form.Field
401 name="firstName"
402 defaultMeta={{ isTouched: true }}
403 validators={{
404 onChangeAsync: async () => {
405 await sleep(10)
406 return onChangeError
407 },
408 onBlurAsync: async () => {
409 await sleep(10)
410 return onBlurError
411 },
412 }}
413 children={(field) => (
414 <div>
415 <input
416 data-testid="fieldinput"
417 name={field.name}
418 value={field.state.value}
419 onBlur={field.handleBlur}
420 onChange={(e) => field.handleChange(e.target.value)}
421 />
422 <p>{field.getMeta().errorMap.onChange}</p>
423 <p>{field.getMeta().errorMap.onBlur}</p>
424 </div>
425 )}
426 />
427 </>
428 )
429 }
430β
431 const { getByTestId, getByText, queryByText } = render(<Comp />)
432 const input = getByTestId('fieldinput')
433β
434 expect(queryByText(onChangeError)).not.toBeInTheDocument()
435 expect(queryByText(onBlurError)).not.toBeInTheDocument()
436 await user.type(input, 'other')
437 await waitFor(() => getByText(onChangeError))
438 expect(getByText(onChangeError)).toBeInTheDocument()
439 await user.click(document.body)
440 await waitFor(() => getByText(onBlurError))
441 expect(getByText(onBlurError)).toBeInTheDocument()
442 })
443β
444 it('should validate async on change with debounce', async () => {
445 type Person = {
446 firstName: string
447 lastName: string
448 }
449 const mockFn = vi.fn()
450 const error = 'Please enter a different value'
451β
452 function Comp() {
453 const form = useForm({
454 defaultValues: {
455 firstName: '',
456 lastName: '',
457 } as Person,
458 })
459β
460 return (
461 <>
462 <form.Field
463 name="firstName"
464 defaultMeta={{ isTouched: true }}
465 validators={{
466 onChangeAsyncDebounceMs: 100,
467 onChangeAsync: async () => {
468 mockFn()
469 await sleep(10)
470 return error
471 },
472 }}
473 children={(field) => (
474 <div>
475 <input
476 data-testid="fieldinput"
477 name={field.name}
478 value={field.state.value}
479 onBlur={field.handleBlur}
480 onChange={(e) => field.handleChange(e.target.value)}
481 />
482 <p>{field.getMeta().errors}</p>
483 </div>
484 )}
485 />
486 </>
487 )
488 }
489β
490 const { getByTestId, getByText } = render(<Comp />)
491 const input = getByTestId('fieldinput')
492 await user.type(input, 'other')
493 // mockFn will have been called 5 times without onChangeAsyncDebounceMs
494 expect(mockFn).toHaveBeenCalledTimes(0)
495 await waitFor(() => getByText(error))
496 expect(getByText(error)).toBeInTheDocument()
497 })
498β
499 it('should handle strict mode properly with conditional fields', async () => {
500 function FieldInfo({ field }: { field: AnyFieldApi }) {
501 return (
502 <>
503 {field.state.meta.isTouched && field.state.meta.errors.length ? (
504 <em>{field.state.meta.errors.join(',')}</em>
505 ) : null}
506 {field.state.meta.isValidating ? 'Validating...' : null}
507 </>
508 )
509 }
510β
511 function Comp() {
512 const [showField, setShowField] = useState(true)
513β
514 const form = useForm({
515 defaultValues: {
516 firstName: '',
517 lastName: '',
518 },
519 onSubmit: async () => {},
520 })
521β
522 return (
523 <div>
524 <form
525 onSubmit={(e) => {
526 e.preventDefault()
527 e.stopPropagation()
528 form.handleSubmit()
529 }}
530 >
531 <div>
532 {/* A type-safe field component*/}
533 {showField ? (
534 <form.Field
535 name="firstName"
536 validators={{
537 onChange: ({ value }) =>
538 !value ? 'A first name is required' : undefined,
539 }}
540 children={(field) => {
541 // Avoid hasty abstractions. Render props are great!
542 return (
543 <>
544 <label htmlFor={field.name}>First Name:</label>
545 <input
546 name={field.name}
547 value={field.state.value}
548 onBlur={field.handleBlur}
549 onChange={(e) => field.handleChange(e.target.value)}
550 />
551 <FieldInfo field={field} />
552 </>
553 )
554 }}
555 />
556 ) : null}
557 </div>
558 <div>
559 <form.Field
560 name="lastName"
561 children={(field) => (
562 <>
563 <label htmlFor={field.name}>Last Name:</label>
564 <input
565 name={field.name}
566 value={field.state.value}
567 onBlur={field.handleBlur}
568 onChange={(e) => field.handleChange(e.target.value)}
569 />
570 <FieldInfo field={field} />
571 </>
572 )}
573 />
574 </div>
575 <form.Subscribe
576 selector={(state) => [state.canSubmit, state.isSubmitting]}
577 children={([canSubmit, isSubmitting]) => (
578 <button type="submit" disabled={!canSubmit}>
579 {isSubmitting ? '...' : 'Submit'}
580 </button>
581 )}
582 />
583 <button type="button" onClick={() => setShowField((prev) => !prev)}>
584 {showField ? 'Hide field' : 'Show field'}
585 </button>
586 </form>
587 </div>
588 )
589 }
590β
591 const { getByText, findByText, queryByText } = render(
592 <StrictMode>
593 <Comp />
594 </StrictMode>,
595 )
596β
597 await user.click(getByText('Submit'))
598 expect(await findByText('A first name is required')).toBeInTheDocument()
599 await user.click(getByText('Hide field'))
600 await user.click(getByText('Submit'))
601 expect(queryByText('A first name is required')).not.toBeInTheDocument()
602 })
603β
604 it('should handle arrays with primitive values', async () => {
605 const fn = vi.fn()
606 function Comp() {
607 const form = useForm({
608 defaultValues: {
609 people: [] as Array<string>,
610 },
611 onSubmit: ({ value }) => fn(value),
612 })
613β
614 return (
615 <div>
616 <form
617 onSubmit={(e) => {
618 e.preventDefault()
619 e.stopPropagation()
620 form.handleSubmit()
621 }}
622 >
623 <form.Field name="people">
624 {(field) => {
625 return (
626 <div>
627 {field.state.value.map((_, i) => {
628 return (
629 <form.Field key={i} name={`people[${i}]`}>
630 {(subField) => {
631 return (
632 <div>
633 <label>
634 <div>Name for person {i}</div>
635 <input
636 value={subField.state.value}
637 onChange={(e) =>
638 subField.handleChange(e.target.value)
639 }
640 />
641 </label>
642 <button
643 onClick={() => field.removeValue(i)}
644 type="button"
645 >
646 Remove person {i}
647 </button>
648 </div>
649 )
650 }}
651 </form.Field>
652 )
653 })}
654 <button onClick={() => field.pushValue('')} type="button">
655 Add person
656 </button>
657 </div>
658 )
659 }}
660 </form.Field>
661 <form.Subscribe
662 selector={(state) => [state.canSubmit, state.isSubmitting]}
663 children={([canSubmit, isSubmitting]) => (
664 <button type="submit" disabled={!canSubmit}>
665 {isSubmitting ? '...' : 'Submit'}
666 </button>
667 )}
668 />
669 </form>
670 </div>
671 )
672 }
673β
674 const { getByText, findByLabelText, queryByText, findByText } = render(
675 <Comp />,
676 )
677β
678 expect(queryByText('Name for person 0')).not.toBeInTheDocument()
679 expect(queryByText('Name for person 1')).not.toBeInTheDocument()
680 await user.click(getByText('Add person'))
681 const input = await findByLabelText('Name for person 0')
682 expect(input).toBeInTheDocument()
683 await user.type(input, 'John')
684β
685 await user.click(getByText('Add person'))
686 const input2 = await findByLabelText('Name for person 1')
687 expect(input).toBeInTheDocument()
688 await user.type(input2, 'Jack')
689β
690 expect(queryByText('Name for person 0')).toBeInTheDocument()
691 expect(queryByText('Name for person 1')).toBeInTheDocument()
692 await user.click(getByText('Remove person 1'))
693 expect(queryByText('Name for person 0')).toBeInTheDocument()
694 expect(queryByText('Name for person 1')).not.toBeInTheDocument()
695β
696 await user.click(await findByText('Submit'))
697 expect(fn).toHaveBeenCalledWith({ people: ['John'] })
698 })
699β
700 it('should handle arrays with subvalues', async () => {
701 const fn = vi.fn()
702 function Comp() {
703 const form = useForm({
704 defaultValues: {
705 people: [] as Array<{ age: number; name: string }>,
706 },
707 onSubmit: ({ value }) => fn(value),
708 })
709β
710 return (
711 <div>
712 <form
713 onSubmit={(e) => {
714 e.preventDefault()
715 e.stopPropagation()
716 form.handleSubmit()
717 }}
718 >
719 <form.Field name="people">
720 {(field) => {
721 return (
722 <div>
723 {field.state.value.map((_, i) => {
724 return (
725 <form.Field key={i} name={`people[${i}].name`}>
726 {(subField) => {
727 return (
728 <div>
729 <label>
730 <div>Name for person {i}</div>
731 <input
732 value={subField.state.value}
733 onChange={(e) =>
734 subField.handleChange(e.target.value)
735 }
736 />
737 </label>
738 <button
739 onClick={() => field.removeValue(i)}
740 type="button"
741 >
742 Remove person {i}
743 </button>
744 </div>
745 )
746 }}
747 </form.Field>
748 )
749 })}
750 <button
751 onClick={() => field.pushValue({ name: '', age: 0 })}
752 type="button"
753 >
754 Add person
755 </button>
756 </div>
757 )
758 }}
759 </form.Field>
760 <form.Subscribe
761 selector={(state) => [state.canSubmit, state.isSubmitting]}
762 children={([canSubmit, isSubmitting]) => (
763 <button type="submit" disabled={!canSubmit}>
764 {isSubmitting ? '...' : 'Submit'}
765 </button>
766 )}
767 />
768 </form>
769 </div>
770 )
771 }
772β
773 const { getByText, findByLabelText, queryByText, findByText } = render(
774 <Comp />,
775 )
776β
777 expect(queryByText('Name for person 0')).not.toBeInTheDocument()
778 expect(queryByText('Name for person 1')).not.toBeInTheDocument()
779 await user.click(getByText('Add person'))
780 const input = await findByLabelText('Name for person 0')
781 expect(input).toBeInTheDocument()
782 await user.type(input, 'John')
783β
784 await user.click(getByText('Add person'))
785 const input2 = await findByLabelText('Name for person 1')
786 expect(input).toBeInTheDocument()
787 await user.type(input2, 'Jack')
788β
789 expect(queryByText('Name for person 0')).toBeInTheDocument()
790 expect(queryByText('Name for person 1')).toBeInTheDocument()
791 await user.click(getByText('Remove person 1'))
792 expect(queryByText('Name for person 0')).toBeInTheDocument()
793 expect(queryByText('Name for person 1')).not.toBeInTheDocument()
794β
795 await user.click(await findByText('Submit'))
796 expect(fn).toHaveBeenCalledWith({ people: [{ name: 'John', age: 0 }] })
797 })
798β
799 it('should handle sync linked fields', async () => {
800 const fn = vi.fn()
801 function Comp() {
802 const form = useForm({
803 defaultValues: {
804 password: '',
805 confirm_password: '',
806 },
807 onSubmit: ({ value }) => fn(value),
808 })
809β
810 return (
811 <div>
812 <form.Field name="password">
813 {(field) => {
814 return (
815 <div>
816 <label>
817 <div>Password</div>
818 <input
819 value={field.state.value}
820 onChange={(e) => field.handleChange(e.target.value)}
821 />
822 </label>
823 </div>
824 )
825 }}
826 </form.Field>
827 <form.Field
828 name="confirm_password"
829 validators={{
830 onChangeListenTo: ['password'],
831 onChange: ({ value, fieldApi }) => {
832 if (value !== fieldApi.form.getFieldValue('password')) {
833 return 'Passwords do not match'
834 }
835 return undefined
836 },
837 }}
838 >
839 {(field) => {
840 return (
841 <div>
842 <label>
843 <div>Confirm Password</div>
844 <input
845 value={field.state.value}
846 onChange={(e) => field.handleChange(e.target.value)}
847 />
848 </label>
849 {field.state.meta.errors.map((err) => {
850 return <div key={err?.toString()}>{err}</div>
851 })}
852 </div>
853 )
854 }}
855 </form.Field>
856 </div>
857 )
858 }
859β
860 const { findByLabelText, queryByText, findByText } = render(<Comp />)
861β
862 const passwordInput = await findByLabelText('Password')
863 const confirmPasswordInput = await findByLabelText('Confirm Password')
864 await user.type(passwordInput, 'password')
865 await user.type(confirmPasswordInput, 'password')
866 expect(queryByText('Passwords do not match')).not.toBeInTheDocument()
867 await user.type(confirmPasswordInput, '1')
868 expect(await findByText('Passwords do not match')).toBeInTheDocument()
869 })
870β
871 it('should handle deeply nested values in StrictMode', async () => {
872 function Comp() {
873 const form = useForm({
874 defaultValues: {
875 name: { first: 'Test', last: 'User' },
876 },
877 })
878β
879 return (
880 <form.Field
881 name="name.last"
882 children={(field) => <p>{field.state.value}</p>}
883 />
884 )
885 }
886β
887 const { queryByText, findByText } = render(
888 <StrictMode>
889 <Comp />
890 </StrictMode>,
891 )
892β
893 expect(queryByText('Test')).not.toBeInTheDocument()
894 expect(await findByText('User')).toBeInTheDocument()
895 })
896β
897 it('should validate async on submit without debounce', async () => {
898 type Person = {
899 firstName: string
900 lastName: string
901 }
902 const mockFn = vi.fn()
903 const error = 'Please enter a different value'
904β
905 function Comp() {
906 const form = useForm({
907 defaultValues: {
908 firstName: '',
909 lastName: '',
910 } as Person,
911 validators: {
912 onChangeAsyncDebounceMs: 1000000,
913 onChangeAsync: async () => {
914 mockFn()
915 await sleep(10)
916 return error
917 },
918 },
919 })
920 const errors = useStore(form.store, (s) => s.errors)
921β
922 return (
923 <>
924 <form.Field
925 name="firstName"
926 defaultMeta={{ isTouched: true }}
927 children={(field) => (
928 <div>
929 <input
930 data-testid="fieldinput"
931 name={field.name}
932 value={field.state.value}
933 onBlur={field.handleBlur}
934 onChange={(e) => field.handleChange(e.target.value)}
935 />
936 <p>{errors}</p>
937 </div>
938 )}
939 />
940 <button onClick={form.handleSubmit}>Submit</button>
941 </>
942 )
943 }
944β
945 const { getByRole, getByText } = render(<Comp />)
946 await user.click(getByRole('button', { name: 'Submit' }))
947β
948 expect(mockFn).toHaveBeenCalledTimes(1)
949 await waitFor(() => getByText(error))
950 expect(getByText(error)).toBeInTheDocument()
951 })
952β
953 it('should validate allow pushvalue to implicitly set a default value', async () => {
954 type Person = {
955 people: Array<string>
956 }
957β
958 function Comp() {
959 const form = useForm({
960 defaultValues: {
961 people: [],
962 } as Person,
963 })
964β
965 return (
966 <form.Field name="people" mode="array">
967 {(field) => {
968 return (
969 <div>
970 <pre>{JSON.stringify(field.state.value)}</pre>
971 {field.state.value.map((_, i) => {
972 return (
973 <form.Field key={i} name={`people[${i}]`}>
974 {(subField) => {
975 return (
976 <div>
977 <label>
978 <div>Name for person {i}</div>
979 <input
980 name={subField.name}
981 value={subField.state.value}
982 onChange={(e) =>
983 subField.handleChange(e.target.value)
984 }
985 />
986 </label>
987 </div>
988 )
989 }}
990 </form.Field>
991 )
992 })}
993 <button onClick={() => field.pushValue('')} type="button">
994 Add person
995 </button>
996 </div>
997 )
998 }}
999 </form.Field>
1000 )
1001 }
1002β
1003 const { getByText, queryByText } = render(
1004 <StrictMode>
1005 <Comp />
1006 </StrictMode>,
1007 )
1008 expect(getByText('[]')).toBeInTheDocument()
1009 await user.click(getByText('Add person'))
1010 expect(getByText(`[""]`)).toBeInTheDocument()
1011 })
1012β
1013 it('should validate allow pushvalue to implicitly set a pushed default value', async () => {
1014 type Person = {
1015 people: Array<string>
1016 }
1017β
1018 function Comp() {
1019 const form = useForm({
1020 defaultValues: {
1021 people: [],
1022 } as Person,
1023 })
1024β
1025 return (
1026 <form.Field name="people" mode="array">
1027 {(field) => {
1028 return (
1029 <div>
1030 <pre>{JSON.stringify(field.state.value)}</pre>
1031 {field.state.value.map((_, i) => {
1032 return (
1033 <form.Field key={i} name={`people[${i}]`}>
1034 {(subField) => {
1035 return (
1036 <div>
1037 <label>
1038 <div>Name for person {i}</div>
1039 <input
1040 name={subField.name}
1041 value={subField.state.value}
1042 onChange={(e) =>
1043 subField.handleChange(e.target.value)
1044 }
1045 />
1046 </label>
1047 </div>
1048 )
1049 }}
1050 </form.Field>
1051 )
1052 })}
1053 <button onClick={() => field.pushValue('Test')} type="button">
1054 Add person
1055 </button>
1056 </div>
1057 )
1058 }}
1059 </form.Field>
1060 )
1061 }
1062β
1063 const { getByText, queryByText } = render(
1064 <StrictMode>
1065 <Comp />
1066 </StrictMode>,
1067 )
1068 expect(getByText('[]')).toBeInTheDocument()
1069 await user.click(getByText('Add person'))
1070 expect(getByText(`["Test"]`)).toBeInTheDocument()
1071 })
1072β
1073 it('should not rerender unrelated fields', async () => {
1074 const renderCount = {
1075 field1: 0,
1076 field2: 0,
1077 }
1078β
1079 function Comp() {
1080 const form = useForm({
1081 defaultValues: {
1082 field1: '',
1083 field2: '',
1084 },
1085 })
1086β
1087 return (
1088 <>
1089 <form.Field name="field1">
1090 {(field) => {
1091 renderCount.field1++
1092 return (
1093 <input
1094 data-testid="field1"
1095 value={field.state.value}
1096 onChange={(e) => field.handleChange(e.target.value)}
1097 />
1098 )
1099 }}
1100 </form.Field>
1101 <form.Field name="field2">
1102 {(field) => {
1103 renderCount.field2++
1104 return (
1105 <input
1106 data-testid="field2"
1107 value={field.state.value}
1108 onChange={(e) => field.handleChange(e.target.value)}
1109 />
1110 )
1111 }}
1112 </form.Field>
1113 </>
1114 )
1115 }
1116β
1117 const { getByTestId } = render(
1118 <StrictMode>
1119 <Comp />
1120 </StrictMode>,
1121 )
1122β
1123 const field1InitialRender = renderCount.field1
1124 const field2InitialRender = renderCount.field2
1125β
1126 await user.type(getByTestId('field1'), 'test')
1127β
1128 // field1 should have rerendered
1129 expect(renderCount.field1).toBeGreaterThan(field1InitialRender)
1130 // field2 should not have rerendered
1131 expect(renderCount.field2).toBe(field2InitialRender)
1132 })
1133})