Skip to content
Advertisement

How to implement button disable function or other technique so that user does not log in twice? react, express

I am trying to prevent users from login in twice and creating 2 sessions (when they press log in button twice very fast). I am thinking of disabling button after it was click and the enabling it after approx. 2 sec in case there was an error e.g. “password incorrect” so that users can reenter their details and send form again. I do currently have onSbumit function (code below) and when I implement onclick disable button it wont send as button is getting disabled before the form is submitted.

What is the best approach to solve that issue? Code of by onSubmit function below:

  handleFormSubmission = (event) => {
    event.preventDefault();

    const credentials = {
      username: this.state.username,
      password: this.state.password,
    };

    if (!this.state.username.trim()) {
      this.setState({
        errorUsername: "*Enter your username.",
      });
    }
    if (!this.state.password.trim()) {
      this.setState({
        errorPassword: "*Enter your password.",
      });
    }
    if (this.state.username.trim() && this.state.password.trim()) {
      this.setState({
        buttonDisable: true,
      });

      login(credentials).then((res) => {
        this.setState({
          buttonDisable: false,
        });
        if (!res.status) {
          this.setState({
            error: res.errorMessage,
          });
        } else {
          localStorage.setItem("accessToken", res.data.accessToken);
          this.props.authenticate(res.data.user);
          this.setState({
            buttonDisabled: true,
          });
          this.props.history.push("/");
        }
      });
    }
  };

Advertisement

Answer

The implementation of the function onClick isn’t necessary, the solution is to stop the user to submit the form twice is to disable the button when you send the data to the server and when you get the response you enable the button:

handleFormSubmission = (event) => {
    event.preventDefault();

    const credentials = {
      username: this.state.username,
      password: this.state.password,
    };

    if (!this.state.username.trim()) {
      this.setState({ errorUsername: "*Enter your username."});
    }
    if (!this.state.password.trim()) {
      this.setState({ errorPassword: "*Enter your password."});
    }
    if (this.state.username.trim() && this.state.password.trim()) {
      setState({
         disableButton: true
      }) //Disable your button here
      login(credentials).then((res) => {
         setState({
         disableButton: false
       }) //enable your button
        if (!res.status) {
          this.setState({error: res.errorMessage});
        } else {
          localStorage.setItem("accessToken", res.data.accessToken);
          this.props.authenticate(res.data.user);
          this.props.history.push("/");
        }
      });
    }
  };
Advertisement