How to get value before user made any changes using onChange

I’m making a login page, and I want to reduce the number of attempts a user has, but only if the new email they entered matches the previous one they had entered i.e the email has not been edited.

I’ve tried comparing the current email state to prevState.email, but they both have the same value anytime a user makes an edit.

Input field:

          <Input
            type="email"
            placeholder="Email"
            value={email}
            onChange={(e) =>
              this.setState({ email: e.target.value, showError: false })
            }
          ></Input>

This is where I check:

      componentDidUpdate(prevProps, prevState) {
        const { isLoginSuccess, loginError } = this.props;
        const { invalidCredentialCount, email} = this.state;
    
        if (
          isLoginSuccess !== prevProps.isLoginSuccess
        ) {
          if (isLoginSuccess) {
          } else if (loginError) {
//it goes into the if statement even after the user makes a change
              if (prevState.invalidCredentialCount > 0 && prevState.email === email) {
                this.setState({
                  invalidCredentialCount: invalidCredentialCount - 1, //reduce count by 1 
                });
              }
          }
        }
      }

I’m quite stuck on how to make this work

Can’t you just keep track of the last submitted email on state and on submission conditionally increment another state variable that keeps track of how many times this has been submitted?

Yes, that’s what I’m trying to do with the variable invalidCredentialCount, which I want to decrease only if both emails are the same. Can you please elaborate what I’m doing wrong or provide some code?

Sure, I came up with something like this:

class App extends React.Component {
  state = {
    pastEmail: '',
    emailSubmitCount: 0,
    currentEmailInput: '',
  }
  
  handleInputChange = e => this.setState({ currentEmailInput: e.target.value })
  
  handleSubmit = () => {
    if (this.state.pastEmail === this.state.currentEmailInput) {
      this.setState(state => ({ emailSubmitCount: state.emailSubmitCount + 1, currentEmailInput: '' }))
    } else {
      this.setState(state => ({ emailSubmitCount: 1, currentEmailInput: '', pastEmail: state.currentEmailInput }))
    }
  }
  
  render() {
    return (
      <div style={ { padding: '20px' } }>
        <h3>Email:</h3>
        <input
          value={ this.state.currentEmailInput }
          onChange={ this.handleInputChange }
        />
        
        <button
          onClick={ this.handleSubmit }
        >
          Submit
        </button>
        <hr />
        <h3>Attempts for email "{ this.state.pastEmail }": { this.state.emailSubmitCount }</h3>
      </div>
    )
  }
}

There is a working pen here.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.