0

I'm tryng to make an api call and store the data in a variable using react hooks (useEffect). The data gets stored in an array, but when I want to render it, nothing gets rendered.

    const [cards, setCards] = useState<ICard[]>([]);
  const [loading, setLoading] = useState<boolean>(true);

  useEffect(() => {
    (async () => {
      try {
        const response = await fetch(apiUrl);
        if (!response.ok) throw new Error('Couldnt find the url');
        setCards(initCards(await response.json()));
        console.log(cards);
        setLoading(false);
      } catch (e) {
        console.error(e.message);
        // TODO: Show error alert
      }
    })();
  }, []);

  const initCards = (cards: Cats[]): ICard[] => {
    let minifiedCards: ICard[] = [];
    for (const card of cards) {
      const { id, url } = card;
      minifiedCards.push({ id, image: url, touched: false });
    }
    console.log(minifiedCards);

    return minifiedCards;
  };

  return (
    <div className="App">
      <ScoreBoard />
      {loading ? 'loading...' : <p>loaded</p>}
      <CardsGrid cards={cards} />
    </div>
  );
const CardsGrid = ({ cards }: CardsGridProps) => (
  <div className="card-grid">
    <h2>Cards Grid</h2>
    {cards.map((card) => {
      card.id;
    })}
  </div>
);
  • 1
    Can you share the whole component? – Dean James Jun 22 '21 at 21:32
  • `const [cards, setCards] = useState([]); const [loading, setLoading] = useState(true); useEffect(() => { (async () => { try { const response = await fetch(apiUrl); if (!response.ok) throw new Error('Couldnt find the url'); setCards(initCards(await response.json())); console.log(cards); setLoading(false); } catch (e) { console.error(e.message); // TODO: Show error alert } })(); }, []);return (
    );`
    – Alejandro QR Jun 22 '21 at 21:55
  • Sorry, I don't really know how to add code in comments – Alejandro QR Jun 22 '21 at 21:56
  • 1
    Comments aren't really for entire code snippets, you can edit your question to include any new details though. – Drew Reese Jun 22 '21 at 21:57
  • @DrewReese Thanks, I've already edited the question to include the whole component (the only thing missing is the api url) – Alejandro QR Jun 22 '21 at 22:04
  • So are you saying that `CardsGrid` isn't rerendering with the updated `cards` state passed in props? Can you update your question to include the `CardsGrid` component code? – Drew Reese Jun 22 '21 at 22:41
  • Yes. I've added the component to the question – Alejandro QR Jun 22 '21 at 22:52

1 Answers1

1

Issue

You don't return anything to render in the CardsGrid component when mapping the cards prop array.

const CardsGrid = ({ cards }: CardsGridProps) => (
  <div className="card-grid">
    <h2>Cards Grid</h2>
    {cards.map((card) => {
      card.id; // <-- nothing returned/mapped to JSX
    })}
  </div>
);

Solution

Return valid JSX from the map callback. Don't forget to include React keys. Here is about the simplest/minimal example.

const CardsGrid = ({ cards }: CardsGridProps) => (
  <div className="card-grid">
    <h2>Cards Grid</h2>
    {cards.map((card) => {
      return (
        <Fragment key={card.id}>
          {card.id}
        </Fragment>
      );
    })}
  </div>
);

You can also implicitly return JSX. Note there is no function body enclosed in curly brackets ({}). (() => { return value; } vs () => value)

const CardsGrid = ({ cards }: CardsGridProps) => (
  <div className="card-grid">
    <h2>Cards Grid</h2>
    {cards.map((card) => (
      <Fragment key={card.id}>
        {card.id}
      </Fragment>
    ))}
  </div>
);
Drew Reese
  • 165,259
  • 14
  • 153
  • 181
  • It's probably cleaner to change `(card) => { return ( ... ) }` into `(card) => ( ... )` within `.map()` which allows you to omit explicit returning. – 3limin4t0r Jun 23 '21 at 01:10
  • @3limin4t0r Totally would be, but code cleanliness wasn't the issue or objective. I wanted to make it overtly clear to the OP that a value *must* be returned by ***explicitly*** returning it. – Drew Reese Jun 23 '21 at 01:33
  • For OP [Arrow function syntax with parentheses instead of curly braces?](https://stackoverflow.com/questions/60596873/arrow-function-syntax-with-parentheses-instead-of-curly-braces) – 3limin4t0r Jun 23 '21 at 01:38