componentDidUpdate with prevState comparision is working on alternate triggers

Viewed 33

I have a main component which is calling another component with some props.

// Main Component

<AnotherComponent
    className="EnterNumber-input"
    submitClicked={this.state.submitClicked}
/>

On click of a button, I'm changing the state (this.state.submitClicked).

<button 
    onClick={async () => {
         await this.setState({submitClicked : !this.state.submitClicked}); 
    }}
>
         Toggle SubmitClicked
</button>

In the other component, I'm comparing the prevState with this.props to show an alert.

componentDidUpdate = (prevProps) => {
        if (this.props.submitClicked && this.props.submitClicked !== prevProps.submitClicked) {
            alert('This alert is being called on alternate changes');
        }
      };

Problem- This alert is visible on alternate button clicks.

Requirement- The alert should appear with every button click.

1 Answers

The offending line is: "if (this.props.submitClicked && this.props.submitClicked !== prevProps.submitClicked) {"

Since this.props.submitClicked is boolean, on every other click, i.e. when the submitClicked state is false, one of the conditions required to display the alert is false, and therefore the alert does not trigger. Since this.props.submitClicked is a boolean, even if the value is defined, if the value is false, this.props.submitClicked evaluates to false.

EDIT:

if you're checking to see if this.props.submitClicked is defined, use: typeof this.props.submitClicked !== 'undefined'

Related