Reputation: 21
I have images array that I get when the component load. I try to filter images by title, so I get the title on the filterByTitle function. I try to filter the images array by axios get results from flickr api.
filterByTitle = title => {
let tempArr = [];
this.state.images.map(image => {
axios
.get(
`https://www.flickr.com/services/rest/?method=flickr.photos.getInfo&api_key={some api key}&photo_id=${
image.id}&format=json&nojsoncallback=1`)
.then(result => {
if (result.data.photo.title._content.indexOf(title) > -1) {
tempArr.push(image);
}
});
});
setTimeout(() => {
this.setState({
images: tempArr // update the images
});
}, 500);
};
I succeed only when I use setTimeOut that wait for the map will end.
I expected to do the same without setTimeOut. I want to setState only when the map will end. How can I do this?
Thanks!
Upvotes: 1
Views: 3726
Reputation: 2365
You want to wait until all prosises are resolved, which is a use case for Promise.all
It should look something like this:
filterByTitle = title => {
let tempArr = [];
let promises = this.state.images.map(image => axios
.get(
`https://www.flickr.com/services/rest/?method=flickr.photos.getInfo&api_key={some api key}&photo_id=${
image.id}&format=json&nojsoncallback=1`)
.then(result => {
if (result.data.photo.title._content.indexOf(title) > -1) {
tempArr.push(image);
}
});
);
Promise.all(promises).then(() => {
this.setState({
images: tempArr // update the images
});
})
};
Upvotes: 1
Reputation: 985
Would this work out for you? Also, the better solution would be to enclose title getting function in a promise and update state after promise gets resolved
filterByTitle = title => {
let tempArr = [];
let imagesLength = this.state.images.length;
let processedLength = 0
this.state.images.map(image => {
axios
.get(
`https://www.flickr.com/services/rest/?method=flickr.photos.getInfo&api_key={some api key}&photo_id=${
image.id}&format=json&nojsoncallback=1`)
.then(result => {
processedLength++;
if (result.data.photo.title._content.indexOf(title) > -1) {
tempArr.push(image);
}
if(processesLength == imagesLength){
this.setState({
images: tempArr // update the images
});
}
});
});
};
Upvotes: 1