reactjsjsonstateundefinedjson-server

Empty object response on fetching data from a local JSON server in React


I`m trying to display the data from a local JSON server but I get into errors.

I know that fetch returns a promise which is asynchronous and it takes couple of milliseconds to succesfully fetch the data but my question is, how can I avoid or ignore the first empty object response and only execute the map on the data when it`s fetched because I get "Cannot read properties of undefined (reading "map)"

function App() {
  const [data, setData] = useState({});
  const [loaded, setLoaded] = useState(false);

  useEffect(() => {
    fetch("http://localhost:8000/data")
      .then((response) => {
        if (!response.ok) {
          throw new Error("Data failed to fetch");
        }
        return response.json();
      })
      .then((data) => {
        setData(data);
        setLoaded(true);
      });
  }, []);

  return (
    <div className="App">
      <Card data={data} loaded={loaded} />
    </div>
  );
}

const Card = ({ data, loaded }) => {
  return (
    <div>
      {data.activeUsers.user432.map((user) => (
        <h1 key={user.id}>{user.id}</h1>
      ))}
    </div>
  );
};

Solution

  • try this -

    { data.activeUsers?.user432.map((user) => (
            <h1 key={user.id}>{user.id}</h1>
          ))}