Denis Stephanov
Denis Stephanov

Reputation: 5231

Return axios response from async service (Vue + Nuxt)

I am trying to return data from axios response from service, but I will always receive from service undefined, but inside service I have data. Can you tell what am I doing wrong?

this is how my service looks like:

import axios from 'axios';

export default {
  async fetchById (articleId) {
    await axios.post('/api/article', { id: articleId })
      .then(function (response) {
        console.log('axios', response) // valid response
        return response.data
      })
      .catch(function (e) {
        console.error('error', e);
      });
  }
}

And there is my usage in component:

async created () {
  const article = await articleService.fetchById('12345')
  console.log('article', article) // there I have undefined
}

Upvotes: 1

Views: 1199

Answers (3)

Ali Chraghi
Ali Chraghi

Reputation: 829

You Can Use callback() function. this is when you pass a function as a parameter into your existing function which will be executed once your axios call has finished. Here is how it would work with your code:

async fetchById (articleId) {
  await axios.post('/api/article', { id: articleId })
  .then(function (response) {
    console.log('axios', response) // valid response
    callback(response.data)
  })
  .catch(function (e) {
    console.error('error', e);
  });
}

Upvotes: 0

fodma1
fodma1

Reputation: 3535

You're missing a return statement

import axios from 'axios';

export default {
  async fetchById (articleId) {
    // Missing `return` in the next line
    return await axios.post('/api/article', { id: articleId })
      .then(function (response) {
        console.log('axios', response) // valid response
        return response.data
      })
      .catch(function (e) {
        console.error('error', e);
      });
  }
}

I'd encourage you to start using TypeScript, these kind of errors can be easily avoided by having proper typings for functions.

Upvotes: 5

Boussadjra Brahim
Boussadjra Brahim

Reputation: 1

In the first example you could use only async/await then return the result :

import axios from 'axios';

export default {

  async fetchById (articleId) {
     try{
     const  response= await axios.post('/api/article', { id: articleId })
        return response.data
      }catch(e){
        console.error('error', e);
        return null;
      };
  }
}

Upvotes: 2

Related Questions