Reputation: 5231
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
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
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
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