I have this promise that is responsible for assigning an image to the items that I bring from another endpoint, it worked fine until I wanted to pass a title parameter to the getImage function, I had to put the for out of it to iterate and pass it for each item but the issue is that then I can not assign img to items because items do not fit inside the then. I guess you should make a chain of promises or something, some advice?
getImage (title) {
var headers = {
method: 'GET',
headers: {
"Api-Key": "xxx",
"cache-control": "no-cache"
}
}
return new Promise((resolve, reject) => {
fetch('https://api.unsplash.com/search/photos?query=${title}&order_by=popular&client_id=xxx', headers)
.then(result => result.json())
.then(data => {
var i = getRandomInt(0, data.results.length);
resolve(data.results[i].urls.small);
});
});
}
getCards (user) {
var _this = this;
fetch(backend+'/getCards/${user.id}')
.then(result => result.json())
.then(items => {
for (var i = 0; i < items.length; i++) {
this.getImage(items[i].title).then(function(result) { //aca items es undefined
items[i].img = result;
});
}
_this.setState({items});
});
}