Call two function onValueChange in React Native
How can I call function DoMath
when TextInput is changed?
state = {
foo: 2,
bar: 3,
Total: 0,
}
DoMath = () =>{
var foo = this.state.foo;
var bar = this.state.bar;
this.state.Total= foo + bar;
this.setState({Total: this.state.Total})
}
<TextInput
onChangeText={(foo) => this.setState({foo})}
value={this.state.foo}
selectTextOnFocus>
</TextInput>
I tried doing onChangeText={(foo) => this.setState({foo}); DoMath;}
but it is not working.
Solution 1:
You need to wrap the body of arrow functions with more than one statement in braces. If you just do onChangeText={(foo) => this.setState({foo}); DoMath;}
, that'll be interpreted as two statements:
What JS sees is:
onChangeText={(foo) => { return this.setState({foo}); }; DoMath;}
So DoMath
gets evaluated when the component is created, but does not get ran when the component's text changes.
Change it to:
onChangeText={(foo) => { this.setState({foo}); DoMath(); } }
and it should work.
Solution 2:
The answer you marked correct might cause you issues, setState is async and DoMath
relies on that updated value. setState offers a callback that will be ran after state gets updated so you will have the updated values when you invoke DoMath
:
handleChangeText = foo => this.setState({ foo }, this.DoMath)
...
...
onChangeText={this.handleChangeText}
Also never do this:
this.state.Total= foo + bar;
this.setState({Total: this.state.Total})
//Do this
const Total= foo + bar;
this.setState({ Total })