I have the following code that works when I uncomment the "return" in fetchData
below. How can I set it up so I wait for this.fetchData
to finish to fill items? I have tried variants of other promises, async, await, but cannot get it to actually work...
So far I set a this.items
inside fetchData
but I realize it's absolutely not what I want to actually do. It shows me the first X lines of my call, because of setting it this way, but all the code that is supposed to happen after the fetchData
call is bugging, starting with trying to do items.length
.
import axios from 'axios';
new Vue({
el: '#app',
data() {
return {
search: '',
totalItems: 0,
items: [],
loading: true,
pagination: {},
headers: [ //some headers
],
items: []
}
},
watch: {
pagination: {
handler () {
this.getDataFromApi()
.then(data => {
this.items = data.items
this.totalItems = data.total
})
},
deep: true
}
},
mounted () {
this.getDataFromApi()
.then(data => {
this.items = data.items
this.totalItems = data.total
})
},
methods: {
fetchData() {
axios.get('/api/v1/translations').then(response => {
//console.log(response.data)
this.items = response.data.data
})
//the return below is working 100%:
//return [{id:1,key:1,lg:'en',text:'woopie'}];
},
getDataFromApi () {
this.loading = true
return new Promise((resolve, reject) => {
const { sortBy, descending, page, rowsPerPage } = this.pagination
let items = this.fetchData()
const total = items.length
//some code to setup pagination and sort
setTimeout(() => {
this.loading = false
resolve({
items,
total
})
}, 1000)
})
}
},
})