Home > Blockchain >  Change state using componentDidUpdate()
Change state using componentDidUpdate()

Time:07-14

Hi i'm trying to change a state using componentDidUpdate() but I get an infinite loop.

componentDidUpdate(prevState) {
    if (prevState.selectedOption1 !== this.state.selectedOption1) {
        this.setState({ disabled2: false });
    }
}

I can´t figure it out

CodePudding user response:

The componentDidUpdate function uses 3 parameters:

  1. previous properties
  2. previous state
  3. snapshot (for when getSnapshotBeforeUpdate() is used.

You are treating the first parameter as previous state, which it is not, this results in your condition always being true and creating your infinite loop as setState is continually called.

To fix the issue correctly use the parameters of componentDidUpdate

componentDidUpdate(
    prevProps, // This is the previous properties 
    prevState // This is the previous state.
) {
    if (prevState.selectedOption1 !== this.state.selectedOption1) {
        this.setState({ disabled2: false });
    }
}

CodePudding user response:

When you change the state, the component updates.

Thus, if you change state state when the component updates then you get your infinite loop.

If you insist on keeping this behavior then you might want to add a boolean check to your state.

  • Related