Search code examples
reactjsnext.jsheadless-cmswp-graphql

How to make a post file using nested getStaticPaths in a category using getStaticPaths? (Using API)


[Next.js] Using Headless CMS WordPress and the plugin [WPGraphQL], I was able to create a list of categories by calling the API in getStaticPaths.

src
--pages
----category
------[slug.tsx] 
--------page
----------[pageNo.tsx]

The following getStaticPaths are described in [slug].tsx

export async function getStaticPaths () {
  const allPosts = await GET_ALL_CATEGORIRS_SLUG ();
  return {
    paths: paths:
      allPosts.edges.map (({node}) => `/category/${node.slug}`) ||
      [],
    fallback: true,
  };
}

The following getStaticPaths are described in [pageNo].tsx

export async function getStaticPaths() {
  const totalCount = await GET_TOTAL_POST_COUNT(currentCategorySlug);
  const totalPostsCount = totalCount.pageInfo.offsetPagination.total ?? 0;

  const pagesCount = Math.ceil(
    (totalPostsCount - PER_PAGE_FIRST) / PER_PAGE_REST + 1
  );

  const paths = new Array(pagesCount).fill("").map((_, index) => ({
    params: {
      pageNo: (index + 1).toString(),
    },
  }));

  return {
    paths: [...paths],
    fallback: true,
  };
}

However, this does not work unless the currentCategorySlug is clear.

How can I get the current parent category?

I can't use useRouter here, so please let me know if there is a way to get the currentCategorySlug or something else. Or do you use useRouter somewhere?


Solution

  • It's a little rough code, but I've solved it, so I'll describe it.

    export async function getStaticPaths() {
      const allCategoryAndPosts = await GET_ALL_CATEGORY_AND_POSTS();
      var paths = new Array();
      allCategoryAndPosts.edges.map(({ node }) => {
        const totalPostsCount = node.posts.pageInfo.offsetPagination.total ?? 0;
        const pagesCount = Math.ceil(
          (totalPostsCount - PER_PAGE_FIRST) / PER_PAGE_REST + 1
        );
        for (let index = 1; index <= pagesCount; index++) {
          paths.push(`/category/${node.slug}/page/${index}` || []);
        }
      });
    
      return {
        paths: [...paths],
        fallback: true,
      };
    }