react-numeric-input icon indicating copy to clipboard operation
react-numeric-input copied to clipboard

onChange triggered by setState

Open thedivac opened this issue 8 years ago • 5 comments

I have an app with many input fields which are depending on each other. For example, when I change the value of input1 then input2 gets changed to input1 * 2 via a setState command. This then triggers another onChange event for the input2. As I have many fields depending on each other this leads to a chain of onChange events. If I use the regular component, this doesn't happen.

My ideas on how to solve the problem:

1st idea: Make it possible to detect if the onchange is triggered by a user input. This way I can ignore the other events which are triggered by setState.

2nd idea: Only trigger onChange events after user inputs similar to the component.

Does anybody have another idea?

thedivac avatar Jun 06 '17 20:06 thedivac

Just saw that issue as well, in my case i have several <NumericInput onChange={} /> and my function in onChange is called automatically for each NumericInput component on page load. I'll try to investigate.

Quick testing (general React):

handleClick = () => {
  console.log('test called')
}

render() {
  return (
    <div>
      <button onClick={this.handleClick()}>calls handleClick</button>
      <button onClick={this.handleClick}>no handleClick call</button>
      <button onClick={() => this.handleClick()}>no handleClick call</button>
    </div>
  );
}

Could be something similar.

kevinch avatar Aug 08 '17 17:08 kevinch

Maybe that's not related to this library specifically. Try onChange={()=> function() } that solved this problem for me (many times)

thedivac avatar Aug 08 '17 17:08 thedivac

Yes i already do this:

<NumericInput
  onChange={valueAsNumber =>
    this.handleInputChange(
      valueAsNumber, param2, param3, param4
    )}
  min={0}

Still calls the function.

kevinch avatar Aug 08 '17 17:08 kevinch

The version that I am currently working on (and that I will try to release soon) should have fixes for this. Meanwhile, if you need urgent fix you can use the guthub version or try this in your node modules:

  1. onChange was called if the component gets re-rendered by it's parent without value prop provided. Fixed here: https://github.com/vlad-ignatov/react-numeric-input/blob/master/src/NumericInput.jsx#L335

  2. Identify the event target - real event is not available for onChange but the input can be passed to onChange - the last argument in: https://github.com/vlad-ignatov/react-numeric-input/blob/master/src/NumericInput.jsx#L366

  3. To listen for user inputs use onInput instead.

vlad-ignatov avatar Aug 08 '17 17:08 vlad-ignatov

This should be fixed in 2.2.0.

vlad-ignatov avatar Aug 20 '17 17:08 vlad-ignatov