Skip to content
Source
Sign inSign up
TanStack/form
Open History to see the last commit

useField.test.tsx

1,275 lines37.4 KB

1/* eslint-disable react-compiler/react-compiler */
2import { describe, expect, it, vi } from 'vitest'
3import { render, waitFor, within } 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>
1002​
1003 const { getByText, queryByText } = render(
1004 <StrictMode>
1005 <Comp />
1006 </StrictMode>,
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>
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)
1045 />
1046 </label>
1047 </div>
1049 }}
1050 </form.Field>
1052 })}
1053 <button onClick={() => field.pushValue('Test')} type="button">
1054 Add person
1055 </button>
1056 </div>
1058 }}
1059 </form.Field>
1062​
1063 const { getByText, queryByText } = render(
1064 <StrictMode>
1065 <Comp />
1066 </StrictMode>,
1068 expect(getByText('[]')).toBeInTheDocument()
1069 await user.click(getByText('Add person'))
1070 expect(getByText(`["Test"]`)).toBeInTheDocument()
1071 })
1072​
1073 it('should handle removing element from array', async () => {
1074 type Person = {
1075 name: string
1076 id: number
1078​
1079 const fakePeople = {
1080 jack: {
1081 id: 5,
1082 name: 'Jack',
1083 },
1084 molly: {
1085 id: 6,
1086 name: 'Molly',
1087 },
1088 george: {
1089 id: 7,
1090 name: 'George',
1091 },
1092 } satisfies Record<string, Person>
1093​
1094 function Comp() {
1095 const form = useForm({
1096 defaultValues: {
1097 people: [fakePeople.jack, fakePeople.molly, fakePeople.george],
1098 },
1099 })
1100​
1101 return (
1102 <form.Field name="people" mode="array">
1103 {(field) => {
1104 return (
1105 <div>
1106 <div data-testid="container">
1107 {field.state.value.map((item, i) => {
1108 return (
1109 <form.Field key={item.id} name={`people[${i}].name`}>
1110 {(subField) => {
1111 return (
1112 <div>
1113 <label>
1114 <div>Name for person {i}</div>
1115 <span>{subField.state.value}</span>
1116 <input
1117 name={subField.name}
1118 value={subField.state.value}
1119 onChange={(e) =>
1120 subField.handleChange(e.target.value)
1122 />
1123 </label>
1124 </div>
1126 }}
1127 </form.Field>
1129 })}
1130 </div>
1131 <button onClick={() => field.removeValue(1)} type="button">
1132 Remove person
1133 </button>
1134 </div>
1136 }}
1137 </form.Field>
1140​
1141 const { getByText, queryByText, getByTestId } = render(
1142 <StrictMode>
1143 <Comp />
1144 </StrictMode>,
1146​
1147 let exisingPeople: Person[] = [
1148 fakePeople.jack,
1149 fakePeople.molly,
1150 fakePeople.george,
1152 exisingPeople.forEach((person) =>
1153 expect(getByText(person.name)).toBeInTheDocument(),
1155 const container = getByTestId('container')
1156 expect(within(container).getAllByRole('textbox')).toHaveLength(3)
1157​
1158 await user.click(getByText('Remove person'))
1159​
1160 expect(within(container).getAllByRole('textbox')).toHaveLength(2)
1161 exisingPeople = [fakePeople.jack, fakePeople.george]
1162 exisingPeople.forEach((person) =>
1163 expect(getByText(person.name)).toBeInTheDocument(),
1165 expect(queryByText(fakePeople.molly.name)).not.toBeInTheDocument()
1166 })
1167​
1168 it('should not rerender unrelated fields', async () => {
1169 const renderCount = {
1170 field1: 0,
1171 field2: 0,
1173​
1174 function Comp() {
1175 const form = useForm({
1176 defaultValues: {
1177 field1: '',
1178 field2: '',
1179 },
1180 })
1181​
1182 return (
1183 <>
1184 <form.Field name="field1">
1185 {(field) => {
1186 renderCount.field1++
1187 return (
1188 <input
1189 data-testid="field1"
1190 value={field.state.value}
1191 onChange={(e) => field.handleChange(e.target.value)}
1192 />
1194 }}
1195 </form.Field>
1196 <form.Field name="field2">
1197 {(field) => {
1198 renderCount.field2++
1199 return (
1200 <input
1201 data-testid="field2"
1202 value={field.state.value}
1203 onChange={(e) => field.handleChange(e.target.value)}
1204 />
1206 }}
1207 </form.Field>
1208 </>
1211​
1212 const { getByTestId } = render(
1213 <StrictMode>
1214 <Comp />
1215 </StrictMode>,
1217​
1218 const field1InitialRender = renderCount.field1
1219 const field2InitialRender = renderCount.field2
1220​
1221 await user.type(getByTestId('field1'), 'test')
1222​
1223 // field1 should have rerendered
1224 expect(renderCount.field1).toBeGreaterThan(field1InitialRender)
1225 // field2 should not have rerendered
1226 expect(renderCount.field2).toBe(field2InitialRender)
1227 })
1228​
1229 it('should handle defaultValue without setstate-in-render error', async () => {
1230 // Spy on console.error before rendering
1231 const consoleErrorSpy = vi.spyOn(console, 'error')
1232​
1233 function Comp() {
1234 const form = useForm({
1235 defaultValues: {
1236 fieldOne: '',
1237 fieldTwo: '',
1238 },
1239 })
1240​
1241 const fieldOne = useStore(form.store, (state) => state.values.fieldOne)
1242​
1243 return (
1244 <form>
1245 <form.Field
1246 name="fieldOne"
1247 children={(field) => {
1248 return (
1249 <input
1250 data-testid={field.name}
1251 id={field.name}
1252 value={field.state.value}
1253 onChange={(e) => field.handleChange(e.target.value)}
1254 />
1256 }}
1257 />
1258 {fieldOne && (
1259 <form.Field
1260 name="fieldTwo"
1261 defaultValue="default field two value"
1262 children={(_) => null}
1263 />
1264 )}
1265 </form>
1268​
1269 const { getByTestId } = render(<Comp />)
1270 await user.type(getByTestId('fieldOne'), 'John')
1271​
1272 // Should not log an error
1273 expect(consoleErrorSpy).not.toHaveBeenCalled()
1274 })