Avidu
Avidu

Reputation: 47

TypeError: Cannot read properties of null (reading 'title') - Graphcms - NextJs

On my Next Js that uses graphCMS as the backend, when I try to get data from the server for the single project page inside [slug].js I get this error. But the same project it works in the index.js file using the .map method.

SS of the error

import { GraphQLClient, gql } from "graphql-request";

const graphcms = new GraphQLClient(
  "api url here"
);

const QUERY = gql`
  query Project($slug: String!) {
    project(where: { slug: $slug }) {
      id
      slug
      title
    }
  }
`;

export const SLUGLIST = gql`
  {
    projects {
      slug
    }
  }
`;

export async function getStaticProps({ params }) {
  const slug = params.slug;

  const data = await graphcms.request(QUERY, { slug });

  const project = data.project;

  return {
    props: {
      project,
    },
  };
}

export async function getStaticPaths() {
  const { projects } = await graphcms.request(SLUGLIST);

  return {
    paths: projects.map((project) => ({ params: { slug: project.slug } })),
    fallback: "blocking",
  };
}

export default function Project({ project }) {
  return (
    <div>
      <h1>This is single project page</h1>
      {/* Project container */}
      <div>
          <div>
            <h1>{project.title}</h1>
          </div>
    </div>
  );
}

Upvotes: 0

Views: 1314

Answers (1)

Tea_Lover_418
Tea_Lover_418

Reputation: 316

From what I can see your GraphQL client is not configured to work yet, since you have an API url of "api url here". It makes sense to me that you can't find the project with these settings.

Consider catching the case that the project is undefined. You can do this in the page with something like this.

if (!project) {
  return <> Project not found </>
}

Or in the original code like this:

<h1>{project?.title || "project title not found"}</h1>

Upvotes: 0

Related Questions