Hie guys, so I have just recently learned about dealing with APIs and decided to create a dog gallery that uses fetch
to get data from an API.
Problem is, even though the app works, I have doubts of whether am following best practice because I am nesting the fetch request inside loops which I think might affect performance. Can some please advice or suggest a better way to do this.
// container is a ul element with 12 generated li items
// createListItem creates a li with a dog image and a breed h2
// These functions respond to search and random button clicks
function generateDogList(breed = 'affenpinscher') {
container.innerHTML = '';
for (let i = 0; i < 12; i++) {
fetch(`https://dog.ceo/api/breed/${breed}/images/random`)
.then(res => res.json())
.then(img => {
createListItem(img.message, breed);
});
}
}
function randomBreeds() {
container.innerHTML = '';
for (let i = 0; i < 12; i++) {
fetch(`https://dog.ceo/api/breeds/list`)
.then(res => res.json())
.then(data => {
let randomBreed =
data.message[Math.floor(Math.random() * (data.message.length - 1))];
fetch(`https://dog.ceo/api/breed/${randomBreed}/images/random`)
.then(res => res.json())
.then(img=> {
createListItem(img.message, randomBreed);
});
});
}
}