Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
826 views
in Technique[技术] by (71.8m points)

next.js - 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.

question from:https://stackoverflow.com/questions/65852823/where-am-i-going-wrong-with-getstaticprops-and-getstaticpaths

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...