Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use multiple nested dynamic routes with getStaticPaths?

Tags:

This is my page tree

├── _app.tsx
├── _document.tsx
├── index.tsx
└── [type]
    └── [slug].tsx

and this is the getStaticPaths for the [slug] page:

export const getStaticPaths: GetStaticPaths = async () => {
  const posts = getAllPosts(["slug"]);

  return {
    paths: posts.map((posts) => {
      return {
        params: {
          type: posts.mainTag,
          slug: posts.slug,
        },
      };
    }),
    fallback: false,
  };
};

so the a page would look like this for example http://localhost:3000/programming/some-slug

when i go to a certain post, i get this error:

A required parameter (type) was not provided as a string in getStaticPaths for /[type]/[slug]

i just don't know how i would go about providing the type parameter to the router.

like image 253
Yassine Bridi Avatar asked May 11 '20 14:05

Yassine Bridi


People also ask

What is fallback in getStaticPaths?

fallback: 'blocking' The paths returned from getStaticPaths will be rendered to HTML at build time by getStaticProps . The paths that have not been generated at build time will not result in a 404 page. Instead, Next. js will SSR on the first request and return the generated HTML .

How do I create a dynamic route in Nextjs?

To create a nested route in Next. js, you need to create a new folder inside the pages folder and save the dynamic route inside it. For example, to create /pages/posts/dynamic-routes-nextjs, save [slug]. js inside /pages/posts.


1 Answers

The sample code above seems correct, so I would try two things:

1) I don't see an await prefix when calling getAllPosts(["slug"]) - this would mean you are returning before you have the data.

Unless that is be design, change to:

const posts = await getAllPosts(["slug"]);

2) There may be a data issue and you missing expected properties. I would suggest you check getStaticPaths by replacing with a simple array:

const Test = (props) => {
    return (
       <>
           {props.slug}
       </>
    );
};

export async function getStaticProps({params}) {
    return {
        props: params
    }
}

export async function getStaticPaths() {
    const posts = [
        {
            mainTag: 'programming',
            slug: 'hello-world'
        },
        {
            mainTag: 'programming',
            slug: 'nextjs-101'
        },
    ];

    return {
        paths: posts.map((posts) => {
            return {
                params: {
                    type: posts.mainTag,
                    slug: posts.slug,
                },
            };
        }),
        fallback: false,
    };
}

export default Test;
like image 192
Samuel Goldenbaum Avatar answered Sep 18 '22 20:09

Samuel Goldenbaum