0

I get a response from a fetch call and i'm trying to check if the respond correspond to a kind of error my server is likely to respond me if the username or the email sent already exist in my database. If this is the case, i try to use a member function of my class to show a error message to the user. But when i try to use my member function i get the error: Unhandled Rejection (TypeError): Cannot read property 'showValidationErr' of undefined.

I think that i can't use a member function in that case, how can i call my member function when i catch a error from my server ?

class RegisterBox extends React.Component {
  constructor(props) {
      super(props);
      this.state = {username: "",
      email: "",
      password: "",
      confirmPassword: "",
      errors: [],
      pwdState: null};
    }

    showValidationErr(elm, msg) {
      this.setState((prevState) => ( {errors: [...prevState.errors, {elm, msg} ] } ) );
    }

    submitRegister(e) {
      fetch("http://localhost:8080/register?user=" + this.state.username + "&psw=" + this.state.password + "&email=" + this.state.email)
            .then(function (respond) {
              return respond.text()
              .then(function(text) {
                if (text === "RegisterError : username") {
                  this.showValidationErr("username", "username allready taken.");
                }
                if (text === "RegisterError : email") {
                  this.showValidationErr("email", "email allready used.");
                }
              })
            });
    }
  }
Muhammad Ovi
  • 1,053
  • 14
  • 26

2 Answers2

1

I found how to correct it. i needed to add the line "var that = this;" at the beginning of my function and use "that.showValidationErr();" instead.

0

In this context, this refers to the anonymous callback function() that you're passing to the then(). Try using the arrow function syntax instead which keeps the this as the surrounding context.

        .then((respond) => {
          return respond.text()
          .then((text) => {
            if (text === "RegisterError : username") {
              this.showValidationErr("username", "username allready taken.");
            }
            if (text === "RegisterError : email") {
              this.showValidationErr("email", "email allready used.");
            }
          })