@@ -17,6 +17,26 @@ const Input: FunctionComponent<
17
17
return children ( inputProps ) ;
18
18
} ;
19
19
20
+ const InputWithCustomOnChange : FunctionComponent <
21
+ {
22
+ children : ( props : ReturnType < typeof useInput > ) => ReactElement ;
23
+ } & InputProps & { setContextValue ?: ( value : string ) => void }
24
+ > = ( { children, setContextValue, ...props } ) => {
25
+ const { getValues } = useFormContext ( ) ;
26
+
27
+ return (
28
+ < Input
29
+ { ...props }
30
+ onChange = { e => {
31
+ props . onChange ( e ) ;
32
+ setContextValue ( getValues ( ) [ props . source ] ) ;
33
+ } }
34
+ >
35
+ { children }
36
+ </ Input >
37
+ ) ;
38
+ } ;
39
+
20
40
describe ( 'useInput' , ( ) => {
21
41
it ( 'returns the props needed for an input' , ( ) => {
22
42
let inputProps ;
@@ -106,6 +126,46 @@ describe('useInput', () => {
106
126
expect ( handleBlur ) . toHaveBeenCalled ( ) ;
107
127
} ) ;
108
128
129
+ it ( 'custom onChange handler should have access to updated context input value' , ( ) => {
130
+ let targetValue , contextValue ;
131
+ const handleChange = e => {
132
+ targetValue = e . target . value ;
133
+ } ;
134
+ const setContextValue = value => {
135
+ contextValue = value ;
136
+ } ;
137
+
138
+ render (
139
+ < CoreAdminContext dataProvider = { testDataProvider ( ) } >
140
+ < Form onSubmit = { jest . fn ( ) } >
141
+ < InputWithCustomOnChange
142
+ source = "title"
143
+ resource = "posts"
144
+ onChange = { handleChange }
145
+ setContextValue = { setContextValue }
146
+ defaultValue = ""
147
+ >
148
+ { ( { id, field } ) => (
149
+ < input
150
+ type = "text"
151
+ id = { id }
152
+ aria-label = "Title"
153
+ { ...field }
154
+ />
155
+ ) }
156
+ </ InputWithCustomOnChange >
157
+ </ Form >
158
+ </ CoreAdminContext >
159
+ ) ;
160
+ const input = screen . getByLabelText ( 'Title' ) ;
161
+
162
+ fireEvent . change ( input , {
163
+ target : { value : 'Changed title' } ,
164
+ } ) ;
165
+ expect ( targetValue ) . toBe ( 'Changed title' ) ;
166
+ expect ( contextValue ) . toBe ( 'Changed title' ) ;
167
+ } ) ;
168
+
109
169
describe ( 'defaultValue' , ( ) => {
110
170
it ( 'applies the defaultValue when input does not have a value' , ( ) => {
111
171
const onSubmit = jest . fn ( ) ;
0 commit comments