Skip to content

Commit

Permalink
(fix) Resolve a bug where a NaN value causes an infinite re-render cy…
Browse files Browse the repository at this point in the history
…cle in the Number input (#406)

* Fix a bug where a NaN value causes an infinite rerender cycle

* Add test coverage
  • Loading branch information
samuelmale authored Oct 3, 2024
1 parent e189897 commit 5316533
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 1 deletion.
9 changes: 8 additions & 1 deletion src/components/inputs/number/number.component.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,13 @@ const NumberField: React.FC<FormFieldInputProps> = ({ field, value, errors, warn
const [lastBlurredValue, setLastBlurredValue] = useState(value);
const { layoutType, sessionMode, workspaceLayout } = useFormProviderContext();

const numberValue = useMemo(() => {
if (isNaN(value)) {
return '';
}
return value ?? '';
}, [value]);

const onBlur = (event) => {
event.preventDefault();
if (lastBlurredValue != value) {
Expand Down Expand Up @@ -57,7 +64,7 @@ const NumberField: React.FC<FormFieldInputProps> = ({ field, value, errors, warn
max={Number(field.questionOptions.max) || undefined}
min={Number(field.questionOptions.min) || undefined}
name={field.id}
value={value ?? ''}
value={numberValue}
onChange={handleChange}
onBlur={onBlur}
allowEmpty={true}
Expand Down
13 changes: 13 additions & 0 deletions src/components/inputs/number/number.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,19 @@ describe('NumberField Component', () => {
expect(screen.getByLabelText('Weight(kg):')).toBeInTheDocument();
});

it('should render with NaN value', async () => {
await renderNumberField({
field: numberFieldMock,
value: NaN,
errors: [],
warnings: [],
setFieldValue: jest.fn(),
});

const inputElement = screen.getByLabelText('Weight(kg):') as HTMLInputElement;
expect(inputElement.value).toBe('');
});

it('calls setFieldValue on input change', async () => {
const mockSetFieldValue = jest.fn();

Expand Down

0 comments on commit 5316533

Please sign in to comment.