Get data from api before rendering component
Alex
I send 2 api requests before rendering the page:
const Profile = {
template: '#profile',
attributes: null,
photos: [],
data: function () {
return {attributes: Profile.attributes, photos: Profile.photos};
},
beforeRouteEnter: function (to, from, next) {
function getProfile() {
return axios.get('user/get-profile?access-token=1', {responseType: 'json'});
}
function getPhotos() {
return axios.get('photos?access-token=1', {responseType: 'json'});
}
axios.all([getProfile(), getPhotos()])
.then(axios.spread(function (profile, photos ) {
console.log(profile, photos );
next(vm => {
vm.setProfile(profile);
vm.setPhotos(photos);
})
}));
},
methods: {
setProfile: function (response) {
Profile.attributes = response.data;
console.log(Profile.attributes);
},
setPhotos: function (response) {
Profile.photos = response.data;
console.log(response);
},
}
};
The problem is that rendering happens before setProfile
and setPhotos
method . How can I render my component correctly?
Phil
Try using async/await. I have removed beforeRouteEnter
and axios.spread
added create
. After all requests are made, the component will be loaded.
const Profile = {
template: '#profile',
attributes: null,
photos: [],
data() {
return {
attributes: null,
photos: null
};
},
async created() {
const getProfile = await axios.get('user/get-profile?access-token=1', {
responseType: 'json'
});
const getPhotos = await axios.get('photos?access-token=1', {
responseType: 'json'
});
this.setProfile(profile);
this.setPhotos(photos);
},
methods: {
setProfile(response) {
this.attributes = response.data;
console.log(this.attributes);
},
setPhotos(response) {
this.photos = response.data;
console.log(response);
}
}
};
Shorter
const Profile = {
template: '#profile',
attributes: null,
photos: [],
data() {
return {
attributes: null,
photos: null
};
},
async created() {
this.attributes = await axios.get('user/get-profile?access-token=1', {
responseType: 'json'
});
this.photo = await axios.get('photos?access-token=1', {
responseType: 'json'
});
}
};