I'm trying to see if I can get some help understanding what I am doing wrong... Im trying to map through the fetched data and I push it to an array called images then after the map is complete then setFullAdLinks to images array. The problem is that it keeps saying that fullAdLinks[0].source is undefined when I call setCurrentImage which is after the getAdLinks() function. I have tried using async methods but I haven't been successful. Any advice would be greatly appreciated!
CodePudding user response:
I think you need Promise.all
, which resolves all the fetch calls and set the state.
const getAdLinks = () => {
const promises = ads.map((ad) => {
return fetch(ad.image)
.then((res) => res.json())
.then((res) => {
let textLink = res[0].caption.rendered.match(regex);
let x = {
adLink: textLink[0],
source: res[0].source_url,
};
return x;
});
});
return Promise.all(promises).then(images => {
setFullAdLinks(images);
})
};
Promise.all
accepts array of Promises, so note the return
statements everywhere.
Refer: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all