0

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

10
  • what you've done look fine -> what's the actual error or problem you are getting? Commented Aug 11, 2020 at 13:48
  • The array images is empty after I iterate over it although props.images does actually have a list of URLs Commented Aug 11, 2020 at 13:55
  • so if you log out props.images it matches the following format?: ['example.com/image.jpg', ...]? it seems weird that you images array would be empty if props.images was not empty Commented Aug 11, 2020 at 14:00
  • this doesnt make any sense. can you post a codesandbox? why and where do you iterate the images array and why would you do that? Commented Aug 11, 2020 at 14:02
  • This is the sandbox but weirdly enough it behaves differently 5zhzo.csb.app This time images is always empty although the request returns data Commented Aug 11, 2020 at 14:21

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

your bottom one has an error because it will try to render a function as you are not calling it

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.