I'm delving into the world of API chaining, specifically trying to link two different API calls within a 'notes' Vue component. My knowledge of promises is basic at best, but I'm eager to enhance my skills in this area.
The initial API call retrieves all notes and stores them in an array using a Vuex mutation. Additionally, during this call, I create an object by mapping users' emails.
With this mapped object in hand, I embark on a second API call within a for loop to fetch all users' avatars.
The structure of the first API call appears like this:
getAllNotesAPI(entity) {
noteService.getNotes(entity)
.then((response) => {
if (response.data.length === '0') {
// Setting 'hasData' to false when response is empty
this.hasData = false;
} else {
// Using a store mutation to add data to the note array
this.setAllNotes(response.data);
}
// Mapping users' emails into 'userEmails'
this.userEmails = [...new Set(response.data.map(x => x.userEmail))];
// Triggering second API call here to retrieve all avatars associated with these emails
for (let i = 0; i < this.userEmails.length; i++) {
this.getAvatarAPI(this.userEmails[i])
}
})
.catch((error) => {
console.log(error);
})
.finally(() => {
this.endLoader('notes');
});
},
this.getAvatarAPI, representing the second API call, follows this format:
getAvatarAPI(login) {
userService.getAvatar(login)
.then((response) => {
let newAvatar = {
userEmail: login,
picture: response.data.picture
};
// Storing the response in a userAvatar Object using a store mutation
this.setUserAvatar(newAvatar);
}).catch((error) => {
console.log(error)
})
},
Although I attempted utilizing async/await, I couldn't grasp how to bind 'this' within an async function (resulting in undefined when calling `this.getAvatarAPI(this.userEmails)`). I also experimented with chaining multiple then methods, but struggled to sequentially: retrieve all notes, fetch all avatars, and terminate the 'note' loader upon completion of both API calls.
If anyone could provide some guidance or a starting point for a solution, it would be greatly appreciated!