Have looked at similar stack overflow answers, but can't figure this one out.
I'm making an API call, which definitely returns an object. When I loop through my data and inject this into the DOM, it appears as a string.
So when I go back to, JSON.parse(data)
my data, it get return the following error:
Uncaught (in promise) SyntaxError: Unexpected token o in JSON at position 1
I know, this is because the data is already turned into a string, but I am not turning into a string anywhere.
Basically, I do not want my elem.largeImageURL
to be injected as a string.
Here's my full JS code. Can't figure what i've done wrong?
function PixabayAPIService() {
const searchURL = 'https://pixabay.com/api/';
const apikey = 'MY_API_KET';
function getImages(carouselContainer) {
fetch(`${searchURL}?key=9656065-${apikey}&q=beautiful+landscape&image_type=photo&page=1&per_page=6`)
.then((res) => {
return res.json();
})
.then((data) => {
console.log('data', data); //HERE TYPEOF DATA IS OBJECT
let result = '';
data.hits.forEach(elem => {
console.log(typeof elem.largeImageURL); //HERE TYPEOF IS STRING
result +=
`<div class="item"><img src="${elem.largeImageURL}" /></div>`;
carouselContainer.append(result);
});
});
}
return {
getImages
};
}
Here's how my console.logs look:
app.js loaded
count 0
data {totalHits: 500, hits: Array(6), total:
7781}hits: (6) [{…}, {…}, {…}, {…}, {…}, {…}]total: 7781totalHits:
500__proto__: Object
object
string
And here is how the DOM is returned - template literals are injected as strings: