Assign the return of a function that returns from a promisse

0

I am exporting a function to another file that is as a webpack-simple + vuejs component, This is the function of api-user.js file:

export function getUsers () {
    axios.post('/api/get_list',{})
    .then(req => {return req.data.list;})
    .catch(err => console.log(err))
}

In the myComponent.vue file, I'm importing it and calling it:

created: async function () {
      this.arrayUsers = await getUsers()
      console.log(this.arrayUsers)

},

But I just get undefined , and I'm not quite sure why.

An example of what I'm trying to do:

link

  

EDIT:

I've got it in a way here, but it's not what I want yet, because it requires a lot of code in the file which I'm trying to keep clean.

api-user.js:

export function getUsers () { 
return axios.post('/apiminer/get_list',{}) 
} 

mycomponent.vue:

created: function() { 

getUsers().then((res) => { 
this.arrayUsers= res.data.list 
}) 
},
    
asked by anonymous 18.03.2018 / 17:14

1 answer

0

I do not know exactly what the error might be, but I'll try to help based on what you reported.

The first error I see is that you have a getUsers() method, however within the method you are performing post , in the axios.post case. In this case there were more errors, such as 405 - Method not Allowed , except for return undefined.

Another problem that can happen is that in Vuejs, I particularly import functions from other files to use them as filters , directly in its <template> tag, and not to call functions within created() .

I might suggest that you try changing this function to be used as a mixin, so it might help solve the problem. See below:

api-users.js

export default {
  methods: {
    getUsers () {
      axios.post('/api/get_list',{})
        .then(req => {return req.data.list;})
        .catch(err => console.log(err))
    }
  }
}

myComponent.vue

In your <template> , enter:

<tr v-for="(item, index) in arrayUsers" v-if="arrayUsers && arrayUsers.length">

Below is the code inside <script> :

import apiUser from "./api-user.js";

export default {
  name: "HelloWorld",
  mixins: [apiUser],
  data() {
    return {
      arrayUsers: []
    };
  },
  created() {
    this.arrayUsers = this.getUsers();
  },      
};

Notes:

  • Correct the import directory of mixin apiUsers ;
  • Verify that your configuration in your main.js or other configuration file, such as port, etc, is correct;
  • Verify that the method name in the backend is correct, as well as its type and the api return, if it is actually being returned in an array of list objects, within the date. Perform some kind of automated test or test it by Postman .
  • I hope I have helped.

        
    18.03.2018 / 18:50