1

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
}

3 Answers 3

5

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Good, i'm agree with you typescript saves the time spent in debugging
thank you, I didnt aware that inner return not returns value from function
2

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;
      };
  }
}

Comments

0

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);
  });
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.