Home > Software engineering >  React cant fetch data from API
React cant fetch data from API

Time:07-13

I want to fetch data from given API(link is censored in code example), but cant manage to to display product.name from my Api fetch.

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

function DataFetching() {
  const [posts, setPosts] = useState([]);
  useEffect(() => {
    axios
      .get("https://CENSORED/")
      .then((res) => {
        console.log(res);
        setPosts(res.data);
      })
      .catch((err) => {
        console.log(err);
      });
  }, []);
  return (
    <div>
      <div>
        {posts.map((post) => (
          <h1>{post.product.name}</h1>
        ))}
      </div>
    </div>
  );
}

Errors enter image description here

CodePudding user response:

The error is because the posts array is empty initially you need to check first if the array has some data then perform a map

setPosts(res.data.product)
{posts?.map((post) => (
   <h1>{post.name}</h1>
))}

or you can use conditional like this

{ posts.length > 0 
 ? posts.map((post) => (
   <h1>{post.name}</h1>
))
 : <Your custom message/>
}

CodePudding user response:

res.data is indicated to be an object in the console.log. the .map method will only work on arrays. If you were expecting an array, make sure you arent hitting the "detail" endpoint, which would return specific information about a post.

  • Related