0

I would like to extract some logic from vue components methods and put them outside in a separate class.

The separate file contains the methods that will call APIs via axios.

When I do that inside the vue component methods, I can get a valid result, but when I do this by calling an outside class method I get a promise.

How to avoid this behavior?

Here are the Code Snippets:

vue component method approach

<script>
const axios = require("axios");
export default {

  methods: {
      
    onChangeAmount(value1, value2, event) {
        
      const value3 = event.target.value;
      const msg = `my_message ?`;
      const myObject = {  'field': value1, 'items': value2, 'day': value3 };
      const answer = confirm(msg);
        
      if (answer) {
        axios
          .put(
            "http://localhost:8000/api/endpoint/" + value1, myObject)
          .then(result => {
            alert(result); //shows valid data
          })
          .catch((error) => {
            if (error.request) {
              const response = JSON.parse(error.request.response);
                alert(response); //shows valid error data
            } else {
              alert(error.message); //shows valid error data
            }
          });
      }
    },
  },
};
</script>

Outside class method approach

<script>

export default {

  methods: {
      
    onChangeAmount(value1, value2, event) {
        
      const value3 = event.target.value;
      const msg = `my_message ?`;
      const stepState = {  'field': value1, 'items': value2, 'day': value3 };
      const answer = confirm(msg);
        
      if (answer) {
            // calling an outside class method
            const output = this.OutSideClass.onChangeAmount((value1, value2, event);
            alert(output); //it shows a Promise
      }
    },
  },
};
</script>

  • 2
    `axios.put()` returns a promise. What you've changed is that instead of handling the result within the promise API (in `.then()`/`.catch()`) you're doing it outside the promise API. Just do `output.then(data => alert(output))` or use `data = await this.OutSideClass.onChangeAmount(); alert(data)` – VLAZ May 03 '21 at 15:28
  • Relevant: [Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference](https://stackoverflow.com/q/23667086) – VLAZ May 03 '21 at 15:29

0 Answers0