Reputation:
In Next.js 12, we got the slug of the current page by doing as below in a getStaticProps
. How can this be done in Next.js 13?
✅Next.js 12
export async function getStaticProps(context) {
const slug = context.params.slug
}
❌Next.js 13 - In Next.js13, using the above code gives this error
Error: Cannot read properties of undefined (reading 'params')
export async function fetchData(context) {
❌const slug = context.params.slug
}
Upvotes: 4
Views: 4935
Reputation: 46251
In the app
directory, your default
exported component, located in a page.js
, gets passed a parameter that would look like this:
{ params: {...}, searchParams: {...} }
If you have a slug
, it would be in params
. But it's your page component that should pass it to your data fetching function, as an example like so:
async function fetchData(context) {
const slug = context.params.slug
}
export default async function Page(context) {
const data = await fetchData(context)
return <h1>My Page</h1>;
}
Upvotes: 4