Skip to content

Commit

Permalink
fix: workaround using a key to reset the input state for invalid numbers
Browse files Browse the repository at this point in the history
  • Loading branch information
MatiasArriola committed Feb 4, 2025
1 parent 3f5f42d commit 5bb67b1
Showing 1 changed file with 11 additions and 2 deletions.
13 changes: 11 additions & 2 deletions src/webapp/components/survey-questions/widgets/NumberWidget.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -18,26 +18,35 @@ const NumberWidget: React.FC<NumberWidgetProps> = props => {
const { onChange: onValueChange, value, numberType } = props;

const [stateValue, setStateValue] = React.useState(value);
React.useEffect(() => setStateValue(value), [value]);
const [inputKey, setInputKey] = React.useState(0);

React.useEffect(() => setStateValue(value), [value]);
const updateState = React.useCallback(({ value }: { value: string }) => {
setStateValue(value);
}, []);

const notifyChange = React.useCallback(
({ value: newValue }: { value: string }) => {
if (newValue === "") {
// change the key in case of "" value, which could mean invalid number for the input
setInputKey(inputKey + 1);
}
if (!isValidNumberValue(newValue, numberType)) {
setStateValue(value);
} else if (value !== newValue) {
onValueChange(newValue);
}
},
[onValueChange, value, numberType]
[onValueChange, value, numberType, setInputKey, inputKey]
);

return (
<>
<Input
// HACK: use a key to force resetting the input value
// input was not updated when in invalid state and stateValue changed to ""
key={inputKey}
type="number"
onBlur={notifyChange}
onChange={updateState}
value={stateValue || ""}
Expand Down

0 comments on commit 5bb67b1

Please sign in to comment.