{
prodName: "Name",
quantity: 5
}
Using quantity property of this object, I am rendering an input on screen like shown below.
<input type="number" value=quantity onChange={this.handleQuantityChange} />
with the handleQuantityChange here:
handleQuantityChange(event) => {
if(event.target.value > 0) updateQuantity(event.target.value);
}
updateQuantity() function triggers an action and updates quantity in database and hence update the JSON which renders the updated quantity on screen.
Till here everything is fine.
The issue is, I am not able to update quantity after a single digit is entered. Like in this example, I can make this quantity from 5 to 51, 52, 53 or 510 or 5200 and so on but I am not able to make it 6 or 7 or 2.
This is happening because of an if condition given in handleQuantityChange function, but I can't remove the condition as API throws an error on sending NaN or 0 value.
Also tried storing this quantity in a localState of component but then the database value and input value do not sync with each other and for updating quantity, we have only one onChange event occurring.
Any method on how to manage this onChange function.
Thanks in advance.
Take a look to the following implementation:
const data = {
prodName: 'Name',
quantity: 5
};
const App = () => {
const [value, setValue] = React.useState(data.quantity); // GET INITIAL VALUE FROM GLOBAL STATE
// THIS WAY YOU MAKE THE INPUT A "CONTROLLED INPUT"
const onChangeHandler = React.useCallback((e) => {
setValue(e.target.value);
}, []);
React.useEffect(() => {
const quantity = parseInt(value);
if (quantity) {
// UPDATE DATABASE HERE!
console.log('NEW VALUE', quantity);
}
}, [value])
return (
<input type={'number'} value={value} onChange={onChangeHandler} />
);
};
ReactDOM.render(<App/>, document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.1/umd/react-dom.production.min.js"></script>
<div id='root'></div>