Skip to content

Commit

Permalink
fix: prevent null or NaN values in number input fields
Browse files Browse the repository at this point in the history
  • Loading branch information
csm-thu committed Apr 20, 2023
1 parent 1879250 commit 1c40ae1
Showing 1 changed file with 21 additions and 3 deletions.
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
// Copyright (c) Cosmo Tech.
// Licensed under the MIT license.

import React from 'react';
import React, { useCallback } from 'react';
import { BasicNumberInput } from '@cosmotech/ui';
import PropTypes from 'prop-types';
import { useTranslation } from 'react-i18next';
Expand All @@ -24,7 +24,14 @@ function getMaxValue(parameterData) {
return parameterData.maxValue;
}

export const GenericNumberInput = ({ parameterData, context, parameterValue, setParameterValue, isDirty }) => {
export const GenericNumberInput = ({
parameterData,
context,
parameterValue,
setParameterValue,
defaultParameterValue,
isDirty,
}) => {
const { t } = useTranslation();
const inputProps = {
min: getMinValue(parameterData),
Expand All @@ -40,14 +47,24 @@ export const GenericNumberInput = ({ parameterData, context, parameterValue, set
value = NaN;
}

// Intercept value setter to prevent setting null, undefined or NaN values and fallback to parameter default value
// instead
const changeValue = useCallback(
(newValue) => {
if (newValue != null && !isNaN(newValue)) setParameterValue(newValue);
else setParameterValue(defaultParameterValue);
},
[defaultParameterValue, setParameterValue]
);

return (
<BasicNumberInput
key={parameterData.id}
id={parameterData.id}
label={t(`solution.parameters.${parameterData.id}`, parameterData.id)}
tooltipText={t(TranslationUtils.getParameterTooltipTranslationKey(parameterData.id), '')}
value={value}
changeNumberField={setParameterValue}
changeNumberField={changeValue}
textFieldProps={textFieldProps}
inputProps={inputProps}
isDirty={isDirty}
Expand All @@ -60,6 +77,7 @@ GenericNumberInput.propTypes = {
context: PropTypes.object.isRequired,
parameterValue: PropTypes.any,
setParameterValue: PropTypes.func.isRequired,
defaultParameterValue: PropTypes.number.isRequired,
isDirty: PropTypes.bool,
};
GenericNumberInput.defaultProps = {
Expand Down

0 comments on commit 1c40ae1

Please sign in to comment.