I am trying to get the images data from flickr. I am getting the response but not able to display the image.I have tried using useEffect to fetch the api and useState variable to store images array. Still it was getting called two times.
const DisplayImages = () => {
let photos = [];
fetch(
` https://www.flickr.com/services/rest/?method=flickr.galleries.getPhotos&api_key=***********************&gallery_id=************&format=json&nojsoncallback=1`
)
.then((response) => response.json())
.then((res) => {
const images = res;
console.log(res);
photos = images.photos.photo;
});
return (
<>
<div className="imagescontainer">
{photos.map((photo) => {
console.log(photo);
let url = `https://farm${photo.farm}.staticflickr.com/${photo.server}/${photo.id}_${photo.secret}`;
<>
{/* <img src={require(url)} alt="img" /> */}
</>
})}
</div>
</>
);
};
I expected the images to be rendered.
It's getting called twice because React is probably configured to be in strict mode (as it should be). In development, strict mode causes hooks to be called twice on purpose. This is intentional and you'll need to write your React components with this in mind.
Second, you're using a locally-scoped variable
photosto hold state, when you need to useuseStateinstance, otherwise React won't know when the state changes and re-render the component.Third, it looks like you're setting
photos, which is initialized with an empty array, to a single instance of a photo.