'Undefined: When I fetch data from graphql in Next.js

I am new to fetching data from graphql in Next.js. When I it gives me undefined. It works fine on the playground but got a problem on next.js.

Here is the graphql API

https://shoplly-api.techawks.io/graphql

Here is the code Hero.js for displaying the categories data.

import { ApolloClient, InMemoryCache, gql } from "@apollo/client";
const Hero = ({ categories }) => {
  console.log(categories);
  return (
    <div>
      <div className="flex space-x-4 justify-center items-center">
        <div>Products</div>
        <div>Contact us</div>
        <div>About us</div>
        <div>Contact us</div>
        <div>About us</div>
      </div>
    </div>
  );
};

export default Hero;

export async function getStaticProps() {
  const client = new ApolloClient({
    uri: "https://shoplly-api.techawks.io/graphql",
    cache: new InMemoryCache(),
  });
  const { data } = await client.query({
    query: gql`
      query {
        categories {
          name
        }
      }
    `,
  });
  console.log(categories);
  return {
    props: {
      categories: data.categories,
    },
  };
}

When I console log categories object it returns undefined? What I actually missed in this case?

Thanks



Solution 1:[1]

As Radosvet mentioned, categories isn't defined in getStaticProps, so that will be undefined there.

In Next.js, getStaticProps is only called from page components. So, if you are using <Hero /> as a regular React component in another page, getStaticProps won't be called, and no props will be passed to Hero. Try either using Hero.js as a page, meaning it should be in the pages directory of your project and go to localhost:3000/hero, or define getStaticProps in whatever page is using that component, and pass the props from the page into Hero. Something like this:

import Hero from "../components/hero";
import { ApolloClient, InMemoryCache, gql } from "@apollo/client";

export default function Home({ categories }) {
  return <Hero categories={categories} />;
}

export async function getStaticProps() {
  const client = new ApolloClient({
    uri: "https://shoplly-api.techawks.io/graphql",
    cache: new InMemoryCache(),
  });
  const { data } = await client.query({
    query: gql`
      query {
        categories {
          name
        }
      }
    `,
  });
  return {
    props: {
      categories: data.categories,
    },
  };
}

Solution 2:[2]

In getStaticProps you are never defining just the categories. Try using data.categories

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 dronan
Solution 2 Radosvet Petrov