Viktor Helfrih
Viktor Helfrih

Reputation: 69

Retrieving data from Strapi v4 and mapping it in ReactJS just returns empty array

I am trying to map data from Strapi, but receiving an empty array. The endpoint works fine through Postman: enter image description here

the custom useFetch just not working:


const useFetch = (url) => {
  const [data, setData] = useState([]);
  const [error, setError] = useState([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    const fetchData = async () => {
      setLoading(true);

      try {
        const res = await fetch(url);
        const json = await res.json();
        setData(json);
        setLoading(false);
      } catch (error) {
        setError(error);
        setLoading(false);
      }
    };

    fetchData();
  }, [url]);

  return { loading, error, data };
};

export default useFetch;

The Homepage.js component:

import useFetch from "../hooks/useFetch";
import { Link } from "react-router-dom";

export default function Homepage() {
  const { loading, error, data } = useFetch("http//localhost:1337/api/recepts");

  if (loading) {
    return <p>Loading...</p>;
  } else if (error === []) {
    return <p>Error</p>;
  }

  return (
    <div>
      {Array.isArray(data) &&
        data?.map((el) => (
          <div key={data.id} className="recept-card">
            <h2>{data.data.attributes.title}</h2>

            <small>console list</small>

            <p>{data.data.attributes.body.substring(0, 200)}</p>
            <Link to={`/details/${data.data.id}`}>...</Link>
          </div>
        ))}
    </div>
  );
}

I don't receive any errors, just empty arrays when logging to the console. I would appreciate any ideas to correct this.

Upvotes: 0

Views: 550

Answers (1)

Ahmad Alfan
Ahmad Alfan

Reputation: 331

I believe you should use el instead of data inside the map returned JSX.

      {Array.isArray(data) &&
        data?.map((el) => (
          <div key={el.id} className="recept-card">
            <h2>{el.attributes.title}</h2>

            <small>console list</small>

            <p>{el.attributes.body.substring(0, 200)}</p>
            <Link to={`/details/${el.id}`}>...</Link>
          </div>
        ))}

Upvotes: 1

Related Questions