简体   繁体   中英

Data fetched from an API is not rendering (React)

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>
);

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>
);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM