0

I am working on a ReactJS application, where I have a JSON which is coming from database and stored inside Redux store.
{
  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.

2
  • You need valueAsNumber. value is a string for all input controls, but numerical ones have the other one as well. Commented Aug 13, 2021 at 12:22
  • According to stackoverflow.com/questions/40920945/… react may not allow it. If still that's the case, try using parseInt() (or parseFloat()) on value. Commented Aug 13, 2021 at 12:28

1 Answer 1

1

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>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.