Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix <NumberInput> parses 0 as string when used with a custom parse prop #8454

Merged
merged 4 commits into from
Dec 1, 2022
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
44 changes: 44 additions & 0 deletions packages/ra-ui-materialui/src/input/NumberInput.spec.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -290,6 +290,50 @@ describe('<NumberInput />', () => {
});
expect(onSubmit.mock.calls[0][0].views).toBeNull();
});

it('should cast value to a numeric with a custom parse function', async () => {
const onSubmit = jest.fn();

render(
<AdminContext>
<SimpleForm toolbar={<MyToolbar />} onSubmit={onSubmit}>
<NumberInput {...defaultProps} parse={value => value} />
</SimpleForm>
</AdminContext>
);
const input = screen.getByLabelText('resources.posts.fields.views');
fireEvent.change(input, { target: { value: '12' } });
fireEvent.click(screen.getByText('ra.action.save'));
await waitFor(() => {
expect(onSubmit).toHaveBeenCalledWith(
{ views: 12 },
expect.anything()
);
});
expect(typeof onSubmit.mock.calls[0][0].views).toEqual('number');
});

it('should cast 0 to a numeric with a custom parse function', async () => {
const onSubmit = jest.fn();

render(
<AdminContext>
<SimpleForm toolbar={<MyToolbar />} onSubmit={onSubmit}>
<NumberInput {...defaultProps} parse={value => value} />
</SimpleForm>
</AdminContext>
);
const input = screen.getByLabelText('resources.posts.fields.views');
fireEvent.change(input, { target: { value: '0' } });
fireEvent.click(screen.getByText('ra.action.save'));
await waitFor(() => {
expect(onSubmit).toHaveBeenCalledWith(
{ views: 0 },
expect.anything()
);
});
expect(typeof onSubmit.mock.calls[0][0].views).toEqual('number');
});
});

describe('onChange event', () => {
Expand Down
15 changes: 8 additions & 7 deletions packages/ra-ui-materialui/src/input/NumberInput.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -83,13 +83,14 @@ export const NumberInput = ({
}
const target = event.target;
setValue(target.value);
const newValue = target.valueAsNumber
? parse
? parse(target.valueAsNumber)
: target.valueAsNumber
: parse
? parse(target.value)
: convertStringToNumber(target.value);
const newValue =
target.valueAsNumber !== undefined
? parse
? parse(target.valueAsNumber)
: target.valueAsNumber
: parse
? parse(target.value)
: convertStringToNumber(target.value);
field.onChange(newValue);
};

Expand Down