Displaying API data in React

I want to display the NASA APOD API data in React. I’ve done it in vanilla JS but I’m having issues doing it in React. When I console log the data, I can see the array of information from the NASA API. However when I try to return anything, it says undefined. I’ve tried photoData.date, data.date, but all are undefined yet I can see the array.

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

const count = 6;
const apiKey = 'myapikey'
const apiURL = `https://api.nasa.gov/planetary/apod?api_key=${apiKey}&count=${count}`;


function Card() {
  const [photoData, setPhotoData] = useState(null);

  useEffect(() => {
    fetchPhoto();

    async function fetchPhoto() {
      const res = await fetch(apiURL);
      const data = await res.json();
      setPhotoData(data);
      console.log(data);
    }
  }, []);


return (

    <React.Fragment>
    <div>
<h1>{photoData.date}</h1>
    </div>
    </React.Fragment>
  );
};

export default Card;

What am I missing here?

photoData should be an array of objects (no data property). You can also log out the data to the DOM using JSON.stringify().

When I console log data in the API call I get the array. How can I display it? Is it not saved to photoData?

If you want to say map the data, you just use map on the photoData. Inside the map callback you have access to each object.


Edit: Remember photoData is an array of objects. So to get to the date property of the first object it would be photoData[0].date

Here is a quick map example:

return (
  <div className="App">
    {photoData &&
      photoData.map((img) => (
        <div className="image-data">
          <h2 className="title">{img.title}</h2>
          <img className="image" src={img.url} alt="Astronomy of the Day" />
          <p className="explanation">{img.explanation}</p>
        </div>
      ))}
  </div>
);