qwertz
qwertz

Reputation: 59

Using map function for array of string

I have an issue where I don't understand what I'm doing wrong. I'm passing array of strings (URLs) to a component and try render Images from those URLs by using the map function but what I'm doing seems to break the array.

function Board(props) {
  let images = props.images.map((imgUrl, index) => {
    return <img key={index} src={imgUrl} alt="img"></img>;
  });
  console.log(images);

  return (
    <div className="Board">
      <p>Board</p>
      {images}
    </div>
  );
}

I'm probably missing something obvious so thanks in advance

Upvotes: 0

Views: 454

Answers (1)

Apostolos
Apostolos

Reputation: 10463

After seeing your url, the problem is here

  useEffect(() => {
    fetch(API)
      .then((response) => response.json())
      .then((data) => data.forEach((entry) => images.push(entry.download_url)));
  });
console.log(images);

images will always be empty. You need to use async/await

  useEffect(() => {
    const fetchData = async () => {
      await fetch(API)
      .then((response) => response.json())
      .then((data) => data.forEach((entry) => images.push(entry.download_url)));

      console.log(images);
      images = images.map((imgUrl, index) => {
        return <img key={index} src={imgUrl} alt="img"></img>;
      });
    };
 
    fetchData();
  }, []);

But there is another problem. You are using a variable not stored in local state which will be lost after next render.

Please see this codesandbox.

https://codesandbox.io/s/thirsty-wood-0r3kw

Initiate your array as

const [images, setImages] = useState([]);

and then update the images array inside the useEffect. This is the correct way.

Upvotes: 3

Related Questions