Anthony
Anthony

Reputation: 387

Where am I going wrong with getStaticProps() and getStaticPaths()?

The Issue

I cannot query the API by slug, it must be by id. An KeystoneJS headless CMS provide the data via API and my NextJS should use this data in a static generated Next.js app. Keystone API must be queried like this:

All Posts: (ALL_POSTS_QUERY)


query {
  allPosts {
    id
    slug
    title
  }
}

Single Post: (POST_QUERY)

query {
  Post(where: { id: $id }) {
   title
   body
  }
}

I do use Apollo Client to connect to the API endpoint.

A query for an individual post must be formatted as described above, with an id variable and that's what seems to be the issue. I need to generate static pages by slug and not by id.

The functions

getStaticPaths()

export const getStaticPaths = async () => {
  const { data } = await apolloClient.query({
    query: ALL_POSTS_QUERY,
  });

  return {
    paths: data.allPosts.map(({ id, slug }) => ({
      params: { slug: slug },
    })),
    fallback: false,
  };
};

getStaticProps()

export const getStaticProps = async ({ params }) => {
  const id = params.id;
  const { data } = await apolloClient.query({
    query: POST_QUERY,
    variables: {
      id,
    },
  });
  return {
    props: {
      term: data.Post,
    },
  };
};

More info about KeystoneJS generated APIs.

Please help

I'm very new to developing so my understanding of this is still basic. Apologies if I've misunderstood the logic. Please can anyone help me with where I'm going wrong with my functions? I wasn't able to find anyone else trying to build dynamic routes by slug but querying the API by id to retrieve that post's data.

Upvotes: 2

Views: 1502

Answers (1)

Gh05d
Gh05d

Reputation: 8982

Your problem is that you want to access the prop id of params, but params.id simply does not exist. What exists is params.slug. If you want to pass through the id, then change your code to this:

export const getStaticPaths = async () => {
  const { data } = await apolloClient.query({
    query: ALL_POSTS_QUERY,
  });

  return {
    paths: data.allPosts.map(({ id, slug }) => ({
      params: { id },
    })),
    fallback: false,
  };
};

Now you are passing through the id instead of the slug and should be fine.

Upvotes: 2

Related Questions