Skip to content

Commit 48cbe2d

Browse files
authored
Merge pull request #8453 from smeng9/fix-numberinput-format
fix format does not get triggered after function change
2 parents 0c3da16 + 4747b4e commit 48cbe2d

File tree

2 files changed

+41
-1
lines changed

2 files changed

+41
-1
lines changed

packages/ra-ui-materialui/src/input/NumberInput.spec.tsx

+40
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ import { fireEvent, render, screen, waitFor } from '@testing-library/react';
33
import { useFormContext, useWatch } from 'react-hook-form';
44

55
import { NumberInput } from './NumberInput';
6+
import { TextInput } from './TextInput';
67
import { AdminContext } from '../AdminContext';
78
import { SaveButton } from '../button';
89
import { SimpleForm, Toolbar } from '../form';
@@ -290,6 +291,45 @@ describe('<NumberInput />', () => {
290291
});
291292
expect(onSubmit.mock.calls[0][0].views).toBeNull();
292293
});
294+
295+
it('should reformat if format function gets changed', async () => {
296+
const AngleInput = props => {
297+
const unit = useWatch({ name: 'unit' });
298+
return (
299+
<NumberInput
300+
format={v =>
301+
unit === 'radian' ? v : (v / Math.PI) * 180
302+
}
303+
{...props}
304+
/>
305+
);
306+
};
307+
308+
const onSubmit = jest.fn();
309+
310+
render(
311+
<AdminContext>
312+
<SimpleForm
313+
defaultValues={{ unit: 'radian', value: Math.PI / 2 }}
314+
onSubmit={onSubmit}
315+
>
316+
<AngleInput resource="posts" source="value" />
317+
<TextInput resource="posts" source="unit" />
318+
</SimpleForm>
319+
</AdminContext>
320+
);
321+
const valueInput = screen.getByLabelText(
322+
'resources.posts.fields.value'
323+
);
324+
const unitInput = screen.getByLabelText(
325+
'resources.posts.fields.unit'
326+
);
327+
fireEvent.change(unitInput, { target: { value: 'degree' } });
328+
329+
await waitFor(() => {
330+
expect((valueInput as HTMLInputElement).value).toEqual('90');
331+
});
332+
});
293333
});
294334

295335
describe('onChange event', () => {

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

+1-1
Original file line numberDiff line numberDiff line change
@@ -68,7 +68,7 @@ export const NumberInput = ({
6868
React.useEffect(() => {
6969
const stringValue = format(field.value);
7070
setValue(value => (value !== stringValue ? stringValue : value));
71-
}, [field.value]); // eslint-disable-line react-hooks/exhaustive-deps
71+
}, [field.value, format]); // eslint-disable-line react-hooks/exhaustive-deps
7272

7373
// update the input text when the user types in the input
7474
const handleChange = (event: React.ChangeEvent<HTMLInputElement>) => {

0 commit comments

Comments
 (0)