Reputation: 23
I'm able to use fetch api (wanted to do the fetch api rather than axios) and call out my local api and console.log the data from my api.js file -
export default {
async getData(){
await fetch(url+"campground")
.then(result => result.json())
.then(data => {
console.log(data) // [{id:123,name:"Shimla"},{id:124,name:"Manali"}]
return data
})
}
}
The issue arises when I try to do it on my Catalogue.vue file.
<script>
import api from '../api';
export default {
name: 'Catalogue',
data() {
return {
camps: null
}
},
methods: {
},
created() {
this.camps = api.getData()
console.log(this.camps) //Promise { <state>: "pending" }
},
}
</script>
The result that I get is usually
Promise { : "pending" }
How can I proceed from here? Thank You
Upvotes: 1
Views: 54
Reputation: 46650
You're not returning anything from getData and because fetch is async you don't need to put async/await on it.
Change to
export default {
getData(){
return fetch(url+"campground")
.then(result => result.json())
}
}
Then because its return value is a promise, you need to await it (as others have said)
async created() {
try {
this.camps = await api.getData()
} catch {
this.camps = []
}
},
or
created() {
api.getData().then(result => this.camps = result).catch(e => this.camps = [])
},
btw, if camps
ends up as an array from the result you should define it as an empty array in data not null
.
Upvotes: 2