0

I was building a react app and got stuck at this issue where my component does not load in the case of a loop. Below is my code for StoriesContainer.js and Story.js. As you will notice I am calling the Story component twice, the first call is outside the loop and that renders perfectly. However, my second call is inside the map loop and that does not seem to work. I am confused about what I might be doing wrong since I tried to look it up online and this was the correct way to do it.

If anyone can help that would be great. The image the result I get right now.

import React, { useState, useEffect } from "react";
import { getStoryID } from "../services/api";
import { Story } from "./Story";

export const StoriesContainer = () => {
  const [data, setData] = useState([]);

  useEffect(() => {
    getStoryID().then((data) => {
      console.log(data);
      setData(data);
    });
  }, []);

  return (
    <>
      <Story id={95666} />
      <h1>App.js</h1>
      <ul>
        {data.map((id) => {
          // eslint-disable-next-line no-lone-blocks
          {
            console.log(id);
          }
          <Story key={id} id={id} />;
        })}
      </ul>
    </>
  );
};
export const Story = ({ id }) => {
  
  return <h1>This is story {id}</h1>;
};

enter image description here

1
  • it's a typo, your map callback has no return statement Commented Jan 13, 2021 at 12:44

2 Answers 2

2

You're not returning from your map callback.

  <ul>
    {data.map((id) => {
      // eslint-disable-next-line no-lone-blocks
      {
        console.log(id);
      }
      return <Story key={id} id={id} />;
    })}
  </ul>

or simply

  <ul>
    {data.map((id) => <Story key={id} id={id} />}
  </ul>

Both will be fine and I will prefer the second one.

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

2 Comments

Wow. Cant believe it was that simple. A follow question: Why does a forEach not work and a map does?
forEach just loops over your array, it does not return anything, you can't, map returns an array, an array of story components, you can mark the question as answered if your problem was solved
1

use the return keyword before <Story> in the map.

Comments

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.