Adrian
Adrian

Reputation: 27

Uncaught (in promise) TypeError: photos.forEach is not a function - Parsing unsplash photo API

Did i missed something? Im still getting this log: Uncaught (in promise) TypeError: photos.forEach is not a function. No idea what Im doing wrong.

    async fetchImages(baseURL){
    const response = await fetch(baseURL, {
        method: 'GET',
        headers:{
            Accept: 'application/json',
            Authorization: this.API_KEY
        }
    });
    const photos = await response.json();
    return photos;
}
GenerateHTML(photos){
    photos.forEach(photo => {
        const item = document.createElement('div');
        item.classList.add('item');
        item.innerHTML = `
        <a href='#'>
            <img src="${photo.urls.small}">
            <h3>${photo.user.name}</h3>
        </a>             
        `;
        this.galleryDiv.appendChild(item);
        
    });
}
async getSearchedImages(e){
    e.preventDefault();
    const searchValue = e.target.querySelector('input').value;
    const baseURL = await `https://api.unsplash.com/search/photos?page=1&query=${searchValue}&client_id=${this.API_KEY}`
    const photos = await this.fetchImages(baseURL);
    this.GenerateHTML(photos);
}

}

Upvotes: 1

Views: 354

Answers (1)

sc0rp1on
sc0rp1on

Reputation: 368

According to the documentation, the response is served as

{
  "total": 133,
  "total_pages": 7,
  "results": [
    //Photos here
   ]
}

So you should change the function GenerateHTML

GenerateHTML(photos){
    photos.results.forEach(photo => {
        const item = document.createElement('div');
        item.classList.add('item');
        item.innerHTML = `
        <a href='#'>
            <img src="${photo.urls.small}">
            <h3>${photo.user.name}</h3>
        </a>             
        `;
        this.galleryDiv.appendChild(item);
        
    });
}

Upvotes: 1

Related Questions