I'd like to have two input numeric fields, value1
and value2
and add the values of those two fields. The sum
will then be saved in this.state.sum
. I also don't want to use a "submit" button. Some code:
import React, { Component } from 'react';
import addNumbers from "./components/addNumbers"
class App extends Component {
constructor() {
super()
this.state = {
value1: 10,
value2: 3,
sum: 13
}
this.handleChange = this.handleChange.bind(this)
}
handleChange(event) {
//first setState call works fine
this.setState({[event.target.name]: event.target.value})
//call addNumbers function
const sum = addNumbers(this.state.value1, this.statevalue2)
//this second setState() call will lag by one step
this.setState({sum: sum})
console.log(newBarData)
}
render() {
return (
<div>
<form>
<input name="value1" type="number" placeholder="10" onBlur={this.handleChange} />
<input name="value2" type="number" placeholder="3" onBlur={this.handleChange} />
</form>
</div>
);
}
}
export default App;
What happens is: the second setState()
call won't be effected until I make a second change on the page. This is quite a common issue, but I'm not sure how to work around it. I'd like for it to be able to proc immediately after the user updates the form. In the actual use-case, there'll be some calculations based on user-input values, then visualized on a graph (plotly.js), and I want to be able to update the graph "live" after each input field change.