Skip to content

Commit 91c8f11

Browse files
committed
Fix ArrayInput subscribe typing
1 parent 8d9b5c4 commit 91c8f11

File tree

1 file changed

+20
-10
lines changed

1 file changed

+20
-10
lines changed

packages/ra-ui-materialui/src/input/ArrayInput/ArrayInput.tsx

Lines changed: 20 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ import {
77
ArrayInputBase,
88
type ArrayInputBaseProps,
99
} from 'ra-core';
10-
import { useFormContext } from 'react-hook-form';
10+
import { useFormContext, useFormState } from 'react-hook-form';
1111
import {
1212
InputLabel,
1313
FormControl,
@@ -89,32 +89,42 @@ export const ArrayInput = (inProps: ArrayInputProps) => {
8989
const parentSourceContext = useSourceContext();
9090
const finalSource = parentSourceContext.getSource(arraySource);
9191
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+
});
9398
React.useEffect(() => {
9499
return subscribe({
95100
formState: {
96101
dirtyFields: true,
97102
errors: true,
98-
isSubmitted: true,
99103
touchedFields: true,
100104
},
101-
callback: ({ dirtyFields, errors, isSubmitted, touchedFields }) => {
105+
callback: ({ dirtyFields, errors, touchedFields }) => {
102106
const error = get(errors ?? {}, finalSource);
103107
const hasBeenInteractedWith =
104108
get(dirtyFields ?? {}, finalSource, false) !== false ||
105109
get(touchedFields ?? {}, finalSource, false) !== false;
106-
const nextDisplayedError =
107-
hasBeenInteractedWith || isSubmitted ? error : undefined;
108110

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+
}
113121
);
114122
},
115123
});
116124
}, [finalSource, subscribe]);
117125

126+
const displayedError =
127+
hasBeenInteractedWith || isSubmitted ? error : undefined;
118128
const displayedErrorMessage = (displayedError?.root?.message ??
119129
displayedError?.message) as any;
120130
const renderHelperText = helperText !== false || !!displayedError;

0 commit comments

Comments
 (0)