简体   繁体   中英

Data from Apollo Query is undefined

I'd like to ask why returned data from Apollo Query is undefined.

Below is my code snippet in Next.js where is the Next.js component Image with src value set to launch.ships[0].image . But it throws me an error: TypeError: Cannot read properties of undefined (reading 'image') and honestly I don't know why?

import Head from "next/head";
import Image from "next/image";
import { ApolloClient, InMemoryCache, gql } from "@apollo/client";
import styles from "../styles/Home.module.css";

export default function Home({ launches }) {
  return (
    <div className={styles.container}>
      <Head>
        <title>Create Next App</title>
        <meta name="description" content="Generated by create next app" />
        <link rel="icon" href="/favicon.ico" />
      </Head>

      <main className={styles.main}>
        <h1 className={styles.title}>SpaceX Launches</h1>

        <p className={styles.description}>Latest launches from SpaceX</p>

        <div className={styles.grid}>
          {launches.map((launch) => {
            console.log(launch);
            return (
              <a
                key={launch.id}
                href={launch.links.video_link}
                className={styles.card}
              >
                <Image src={launch.ships[0].image} alt="Ship image" />s
                <h3>{launch.id}</h3>
                <p>
                  <strong>Launch Date:</strong>
                  {new Date(launch.launch_date_local).toLocaleDateString(
                    "en-US"
                  )}
                </p>
              </a>
            );
          })}
        </div>
      </main>

      <footer className={styles.footer}>
        <a
          href="https://vercel.com?utm_source=create-next-app&utm_medium=default-template&utm_campaign=create-next-app"
          target="_blank"
          rel="noopener noreferrer"
        >
          Powered by{" "}
          <span className={styles.logo}>
            <Image src="/vercel.svg" alt="Vercel Logo" width={72} height={16} />
          </span>
        </a>
      </footer>
    </div>
  );
}

export async function getStaticProps() {
  const client = new ApolloClient({
    uri: "https://api.spacex.land/graphql/",
    cache: new InMemoryCache(),
  });

  const { data } = await client.query({
    query: gql`
      query GetLaunches {
        launchesPast(limit: 10) {
          id
          mission_name
          launch_date_local
          launch_site {
            site_name_long
          }
          links {
            article_link
            video_link
            mission_patch
          }
          rocket {
            rocket_name
          }
          ships {
            image
          }
        }
      }
    `,
  });

  return {
    props: {
      launches: data.launchesPast,
    },
  };
}

Here is the compiled query from GraphQL:

{
  "data": {
    "launchesPast": [
      {
        "id": "109",
        "mission_name": "Starlink-15 (v1.0)",
        "launch_date_local": "2020-10-24T11:31:00-04:00",
        "launch_site": {
          "site_name_long": "Cape Canaveral Air Force Station Space Launch Complex 40"
        },
        "links": {
          "article_link": null,
          "video_link": "https://youtu.be/J442-ti-Dhg",
          "mission_patch": "https://images2.imgbox.com/d2/3b/bQaWiil0_o.png"
        },
        "rocket": {
          "rocket_name": "Falcon 9"
        },
        "ships": [
          {
            "image": "https://i.imgur.com/MtEgYbY.jpg"
          },
          {
            "image": "https://imgur.com/NHsx95l.jpg"
          },
          {
            "image": "https://i.imgur.com/7VMC0Gn.jpg"
          },
          {
            "image": "https://i.imgur.com/ABXtHKa.jpg"
          }
        ]
      },
      {
        "id": "108",
        "mission_name": "Sentinel-6 Michael Freilich",
        "launch_date_local": "2020-11-21T09:17:00-08:00",
        "launch_site": {
          "site_name_long": "Vandenberg Air Force Base Space Launch Complex 4E"
        },
        "links": {
          "article_link": "https://spaceflightnow.com/2020/11/21/international-satellite-launches-to-extend-measurements-of-sea-level-rise/",
          "video_link": "https://youtu.be/aVFPzTDCihQ",
          "mission_patch": null
        },
        "rocket": {
          "rocket_name": "Falcon 9"
        }

Thank you for your help.

I'd need to see more code to be sure but possibly some launches doesn't have ships . You could do something like this:

   <div className={styles.grid}>
      {launches.map((launch) => {
        console.log(launch);
        return (
          <a
            key={launch.id}
            href={launch.links.video_link}
            className={styles.card}
          >
            {(launch.ships && launch.ships.length > 0) &&
               <Image src={launch.ships[0].image} alt="Ship image" />
            }
            <h3>{launch.id}</h3>
            <p>
              <strong>Launch Date:</strong>
              {new Date(launch.launch_date_local).toLocaleDateString(
                "en-US"
              )}
            </p>
          </a>
        );
      })}
    </div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM