I want to update state with value I'm getting from child component but for some strange reason I will get loop error if I'm using setstate
in my method. Here is my code snippet:
class ParentTab extends Component {
constructor(props) {
super(props);
this.state = {
displayVal : '0',
};
}
totalRec = value => {
console.log('value', value); // will show the value '2' after getting it from ChildTab component
if (value) {
// will cause infinite loop error
this.setState({
displayVal: value.toString(),
});
}
}
render() {
console.log('totalRec', this.totalRec()); // will show undefined because there is delay in getting the value.
return (
<div>
<ChildTab totalRow={this.totalRec} {...this.props} />
/>
Value: {this.state.displayVal} // will show undefined
</div>
);
}
}
ChildTab
component will be getting value from database so there will be delay. Whole page will be render first and so this.totalRec()
is undefined. That's why I want to use state
to rerender it.
However if totalRec()
method is triggered, I will be getting react
loop error when I try to use this.setState
in totalRec()
method.
How do I solve this problem? Thanks in advance.