Aman
Aman

Reputation: 197

.map is not getting re-rendered after updating the state

I have fetched data using useEffect, and also getting the data on console. I've called the setState method to update the state, but the .map function is not working. Even on the console nothing is happening.

 import React, { useState, useEffect } from "react";


function HomePage() {
  const [isFlipped, setIsFlipped] = useState(false);

  const [cardData, setCardData] = useState([]);

  // useEffect function
  useEffect(async () => {
    const url = "https://rickandmortyapi.com/api/character";

    const fetchData = async () => {
      try {
        const response = await fetch(url);
        const json = await response.json();
        const jsonData = json.results;
        setCardData(jsonData);
        console.log(jsonData);
      } catch (error) {
        console.log("error", error);
      }
    };
    fetchData();
  }, []);

  const handleClick = () => {
    setIsFlipped(!isFlipped);
  };

  return (
    <>
      
      {cardData.map((c) => {
        <h1>{c.id}</h1>;
      })}
     
    </>
  );
}

export default HomePage;

Upvotes: 5

Views: 4203

Answers (1)

jsonderulo
jsonderulo

Reputation: 1464

Your code has a few errors:

  1. You dont need/ cant use async keyword on useEffect callback, just declare the function and call it.
  2. The main issue, your map never returns anything.
  3. Not as important, but if you initialize cardData to null, you can check if it is truthy before mapping over it.
  4. As to why nothing shows up in console, setState is async/ a request to update the state for the next render, therefor, the state changes cannot be observed immediately

The following code works in code sandbox let me know if you have any questions.

export default function HomePage() {  {
  const [isFlipped, setIsFlipped] = useState(false);

  const [cardData, setCardData] = useState(null);

  // useEffect function
  useEffect(() => { //removed async here
    const url = "https://rickandmortyapi.com/api/character";

    const fetchData = async () => {
      try {
        const response = await fetch(url);
        const json = await response.json();
        const jsonData = json.results;
        setCardData(jsonData);
        console.log(jsonData);
      } catch (error) {
        console.log("error", error);
      }
    };
    fetchData();
  }, []);

  const handleClick = () => {
    setIsFlipped(!isFlipped);
  };

  return (
    <>
      {cardData && cardData.map((c) => {
        return <h1>{c.id}</h1>; //note here: return keyword
      })}
    </>
  );
}

Upvotes: 2

Related Questions