Home > Back-end >  Why data fetched from backend shows in console but not in the webpage?
Why data fetched from backend shows in console but not in the webpage?

Time:12-29

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;

CodePudding user response:

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

CodePudding user response:

You can remove the bracket on the map:

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

CodePudding user response:

You're not returning anything. Either explicitly use the return keyword to return the element or You can do this in a more appropriate way like this.

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