Search code examples
node.jsreactjsreact-hooksfetch

Why data fetched from backend shows in console but not in the webpage?


Here I've fetched workouts from backend through api. It shows output in the console but unable to map through workouts state in the webpage.

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

const Home = () => {
  const [workouts, setWorkouts] = useState([]);

  useEffect(() => {
    const fetchWorkouts = async () => {
      const response = await fetch("http://localhost:4000/api/workouts");
      const json = await response.json();

      if (response.ok) {
        console.log('success');
        console.log(json);
        setWorkouts(json);
      }
    };

    fetchWorkouts();
  }, []);

  return (
    <div className="home">
      <div className="workouts">
        {workouts &&
          workouts.map((workout) => {
            <p key={workout._id}>{workout.title}</p>;
          })}
      </div>
    </div>
  );
};

export default Home;

Solution

  • You forgot to return it. Do this:

     return <p key={workout._id}>{workout.title}</p>;
    

    or you can also do this:

    {workouts?.map((workout) => (
            <p key={workout._id}>{workout.title}</p>
        ))}