0
votes

i'm new using reactjs. I'm using a Select element with onChange handle. I save the selected value with setState: productFilterChosenValue. Then with handleClick on my button "onClick" event, i do the

this.setState({
  productFilterChosenValue: this.state.productFilterValue,
});

So i have productFilterChoseValue updating his value only on click with the current Select value. And it works fine, because if in my render() function i put {this.state.productFilterValue} then it will show value changing only on button click.

But if I add a component (my own component) in the bottom, giving it as prop the same value

<FetchedTableGrid
     apiRoute={
       this.state.productFilterChosenValue
     }
/>

It will update only after 2 clicks. So I have my value printed and working correctly and the same value as prop that changes state on second click.

Inside my FetchedTableGrid component, I have put console.log(this.props); trying componentDidMount and componentWillReceiveProps getting same error. If I use componentWillUpdate or componentDidUpdate it gets infinity looped.

1
It will be helpful if you can provide the snippet of code for this problem. so we can reproduce this issue - Khant

1 Answers

0
votes

You can not do it this way. The problem is, that if you set the state, then the state updates and since the setState function depends explicitly on the state it get's recalled. Hence an infinite loop.

What you have to do, is passing the previous value as an input to setState:

this.setState((prevState) => ({
  productFilterChosenValue: prevState.productFilterValue,
}));