Search code examples
reactjsjsonrestreact-hooksjsonobjectrequest

How to destructure desired information from NASA IMAGES API using React


I am trying to build a react gallery using NASA Images API. I have been able to get the images and nasa_id from the API, but I am having trouble destructuring the title and description. I haven't worked with many API's, and I don't understand the format of this response. Any further reading or advice would be helpful, but for right now I need help figuring out how to get the response I need for rendering "title" and "description". Specifically, the first colon in "AVAIL:Description" : "some description" is what is throwing me off. I have looked at all of the other endpoints available from the API, but none of them seem to have the all of the same information for the images, at least not that I have found.

Nasa Images API

example metadata response

https://images.nasa.gov/

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

import { Link, useParams } from "react-router-dom";
import api from "../utils/api";
import Preloader from "./Preloader";

export default function Details({ isLoaded }) {
  const { nasa_id } = useParams();
  const [image, setImage] = useState([]);
  const [details, setDetails] = useState([]);

  useEffect(() => {
    api
      .getImage(nasa_id)
      .then(({ collection: { items: item } }) => {
        setImage(item[0]);
      })
      .catch((err) => console.error(err));
  }, []);

  useEffect(() => {
    api
      .getDetails(nasa_id)
      .then(({ Collection: { AVAIL:Description: description } }) => {
        setDetails(description);
        console.log(description);
      })
      .catch((err) => console.error(err));
  }, []);

  return (
    <article className="details">
      <img
        className="details__image"
        src={isLoaded ? image.href : <Preloader />}
        alt=""
      />
      <h2 className="details__title">Title: </h2>
      <p className="details__subtitle">NASA ID: {nasa_id}</p>
      <p className="details__info">Description: {details}</p>
      <nav>
        <Link to="/" className="details__info link">
          Home
        </Link>
      </nav>
    </article>
  );
}


Solution

  • The response from metadata API doesn't contain Collection property. To extract the description and title use quotes:

    .then(({ "AVAIL:Description": description, "AVAIL:Title": title }) => {
    

    Working example