I'm using Next.js, Apollo and GraphQL to fetch data from GraphCMS — and have successfully managed to do that. But now I'm trying to set up a dynamic route [slug].js inside my posts page (that is inside the pages folder) and I'm having a hard figuring it out. There are many posts here about it but I wasn't able to follow along and fix my issue.
These are my dependencies in case that's useful:
"dependencies": {
"@apollo/client": "^3.6.9",
"framer-motion": "^7.3.6",
"graphql": "^16.6.0",
"graphql-request": "^5.0.0",
"next": "^12.3.1",
"react": "^18.2.0",
"react-dom": "^18.2.0"
}
And this is my [slug].js file.
import client from "../../apolloClient";
import { gql } from "@apollo/client";
export default function BlogPostPage({ posts }) {
return <div>{posts.title}</div>;
}
export async function getStaticPaths() {
const { data } = await client.query({
query: gql`
query {
posts {
slug
}
}
`,
});
const { posts } = data;
const paths = posts.map((post) => ({
params: { slug: [post.slug] },
}));
console.log(paths);
return { paths, fallback: false };
}
export async function getStaticProps(params) {
const slug = params.slug[0];
const { data } = await client.query({
query: gql`
query PostBySlug($slug: String!) {
posts(where: { slug: $slug }) {
content {
raw
}
date
id
slug
title
coverImage {
url
}
}
}
`,
variables: { slug },
});
const { posts } = data;
const post = posts[0];
console.log(post);
return { props: { post } };
}
The error I get is TypeError: Cannot read properties of undefined (reading '0') caused by const slug = params.slug[0];.
My console.log(paths) shows this:
[{params: {slug: [Array] } }, { params: {slug: [Array] } } ]
I've noticed changing the file name from [...slug].js to [slug].js] changes the error I get to Error: A required parameter (slug) was not provided as a string in getStaticPaths for /posts/[slug]. In this scenario I tried to do params: {slug: [post.slug].toString() but then I get the same typeError as before.
Any ideas of what could be happening and how to fix it? Thanks in advance!