|
7 | 7 | ArrayInputBase, |
8 | 8 | type ArrayInputBaseProps, |
9 | 9 | } from 'ra-core'; |
10 | | -import { useFormContext } from 'react-hook-form'; |
| 10 | +import { useFormContext, useFormState } from 'react-hook-form'; |
11 | 11 | import { |
12 | 12 | InputLabel, |
13 | 13 | FormControl, |
@@ -89,32 +89,42 @@ export const ArrayInput = (inProps: ArrayInputProps) => { |
89 | 89 | const parentSourceContext = useSourceContext(); |
90 | 90 | const finalSource = parentSourceContext.getSource(arraySource); |
91 | 91 | const { subscribe } = useFormContext(); |
92 | | - const [displayedError, setDisplayedError] = React.useState<any>(); |
| 92 | + const { isSubmitted } = useFormState(); |
| 93 | + const [{ error, hasBeenInteractedWith }, setArrayInputState] = |
| 94 | + React.useState({ |
| 95 | + error: undefined, |
| 96 | + hasBeenInteractedWith: false, |
| 97 | + }); |
93 | 98 | React.useEffect(() => { |
94 | 99 | return subscribe({ |
95 | 100 | formState: { |
96 | 101 | dirtyFields: true, |
97 | 102 | errors: true, |
98 | | - isSubmitted: true, |
99 | 103 | touchedFields: true, |
100 | 104 | }, |
101 | | - callback: ({ dirtyFields, errors, isSubmitted, touchedFields }) => { |
| 105 | + callback: ({ dirtyFields, errors, touchedFields }) => { |
102 | 106 | const error = get(errors ?? {}, finalSource); |
103 | 107 | const hasBeenInteractedWith = |
104 | 108 | get(dirtyFields ?? {}, finalSource, false) !== false || |
105 | 109 | get(touchedFields ?? {}, finalSource, false) !== false; |
106 | | - const nextDisplayedError = |
107 | | - hasBeenInteractedWith || isSubmitted ? error : undefined; |
108 | 110 |
|
109 | | - setDisplayedError(previousError => |
110 | | - isEqual(previousError, nextDisplayedError) |
111 | | - ? previousError |
112 | | - : nextDisplayedError |
| 111 | + setArrayInputState(previousState => |
| 112 | + isEqual(previousState, { |
| 113 | + error, |
| 114 | + hasBeenInteractedWith, |
| 115 | + }) |
| 116 | + ? previousState |
| 117 | + : { |
| 118 | + error, |
| 119 | + hasBeenInteractedWith, |
| 120 | + } |
113 | 121 | ); |
114 | 122 | }, |
115 | 123 | }); |
116 | 124 | }, [finalSource, subscribe]); |
117 | 125 |
|
| 126 | + const displayedError = |
| 127 | + hasBeenInteractedWith || isSubmitted ? error : undefined; |
118 | 128 | const displayedErrorMessage = (displayedError?.root?.message ?? |
119 | 129 | displayedError?.message) as any; |
120 | 130 | const renderHelperText = helperText !== false || !!displayedError; |
|
0 commit comments