Home > database >  Return of validate function not working with axios
Return of validate function not working with axios

Time:10-21

I am trying to make a form, where users can change their email address of the account. I want them to enter their password to validate them. So I have a function that is doing the email change, but before it calls the validate function. If the return value is true it goes on. If not an error appears. But when testing it with the correct credentials it always goes into the else although i get a valid axios response.

    emailChange() {
      if (this.validate() == true) {
        var data = JSON.stringify({
          email: this.email,
        });
        this.put(data);
      } else {
        this.error = "Falsches Passwort";
        this.snackbar = true;
      }
    },

    validate() {
      var data = JSON.stringify({
        identifier: this.loggedInUser.email,
        password: "123456",
      });

      var config = {
        method: "post",
        url: "http://192.168.190.112:1337/api/auth/local",
        headers: {
          "Content-Type": "application/json",
        },
        data: data,
      };

      this.$axios(config)
        .then(function (response) {
          console.log(JSON.stringify(response.data));
        })
        .then(function () {
          return true;
        })
        .catch(function (error) {
          console.log(error);
        });
    },

CodePudding user response:

The function return is not returning to validate. Axios is asynchronous and you need either a promise or a callback.

      this.$axios(config)
        .then(function (response) {
          console.log(JSON.stringify(response.data));
        })
        .then(function () {
          return true; // this does not return to validate(). it returns just here
        })
        .catch(function (error) {
          console.log(error);
        });

This is a way to implement it.

    emailChange() {
      this.validate((error, isValid) => {
        if (isValid) {
          var data = JSON.stringify({
            email: this.email,
          });
          this.put(data);
        } else {
          this.error = "Falsches Passwort";
          this.snackbar = true;
        }
      })
    },

    validate(callback) {
      var data = JSON.stringify({
        identifier: this.loggedInUser.email,
        password: "123456",
      });

      var config = {
        method: "post",
        url: "http://192.168.190.112:1337/api/auth/local",
        headers: {
          "Content-Type": "application/json",
        },
        data: data,
      };

      this.$axios(config)
        .then(function (response) {
          console.log(JSON.stringify(response.data));
        })
        .then(function () {
          callback(null, true);
        })
        .catch(function (error) {
          callback(error);
        });
    }

CodePudding user response:

I think you're misunderstanding the purpose of .then().

Creating a request isn't instant, and it's completion depends on the server you're requesting data from to send you back a response. Because of this, axios uses asynchronous code to give you a Promise that will resolve after the request is complete.

The callback within the .then() function is called whenever the request is resolved (which could take multiple seconds with a slow connection).

The callback that contains your return statement could be called multiple seconds after your validate function ends, which isn't what you want.

I'd suggest using async/await as an alternative.

Declaring a function as async makes it return a Promise no matter what, which is what you want, and await waits for a promise to resolve before continuing.

Here's a quick example

// This function returns a promise!
async validate() {
  // axios.get() returns a promise, so we use await to wait until it's resolved
  let response = await axios.get("url") 

  // return the data (this is not a promise)
  // since the method is async, this will be automatically converted into a promise
  // that will resolve when the method returns something
  return response;
}

// you can only use "await" in async functions
async emailChange() {
  // wait until this.validate() is finished before continuing
  if(await this.validate() == true) {
    // etc.
  }
}

async/await is generally the preferred way to do this because it's much cleaner than chaining callbacks together with .then()

Hopefully this helps

  • Related