Can anyone explain.Why the 'res" is getting logged two times?

39 Views Asked by At

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.

1

There are 1 best solutions below

2
Robin Daugherty On

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 photos to hold state, when you need to use useState instance, 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.