I am trying to access a dynamic route parameter from the layout but the usual params
object is undefined
.
I have this URL: http://localhost:3000/Site/about-us
And this is my file structure:
- app
- (site)
- [siteUrl]
- about-us
- page.tsx
- about-us
- layout.tsx
- [siteUrl]
- (site)
Currently, I can access the page on app/(site)/[siteUrl]/about-us/page.tsx
because I am fetching some data from the database there. But I want to do it from /app/(site)/layout.tsx
and pass it to the child components, context I guess?
This is my layout.tsx
file right now:
import { notFound } from "next/navigation"
import "./globals.css"
import prisma from "@/lib/prisma"
export default async function SiteLayout({
children,
params
}: {
children: React.ReactNode,
params: Promise<{ siteUrl: string }>
}) {
const siteUrl = (await params).siteUrl
if (!siteUrl) {
notFound()
}
const site = await prisma.site.findUnique({
where: {
siteUrl
}
})
if (!site) {
notFound()
}
return (
<html lang="es">
<body>
{children}
</body>
</html>
)
}
I have multiple issues here, but the main issue is that I can't access the siteUrl
variable. Any suggestions?
I am trying to access a dynamic route parameter from the layout but the usual params
object is undefined
.
I have this URL: http://localhost:3000/Site.com/about-us
And this is my file structure:
- app
- (site)
- [siteUrl]
- about-us
- page.tsx
- about-us
- layout.tsx
- [siteUrl]
- (site)
Currently, I can access the page on app/(site)/[siteUrl]/about-us/page.tsx
because I am fetching some data from the database there. But I want to do it from /app/(site)/layout.tsx
and pass it to the child components, context I guess?
This is my layout.tsx
file right now:
import { notFound } from "next/navigation"
import "./globals.css"
import prisma from "@/lib/prisma"
export default async function SiteLayout({
children,
params
}: {
children: React.ReactNode,
params: Promise<{ siteUrl: string }>
}) {
const siteUrl = (await params).siteUrl
if (!siteUrl) {
notFound()
}
const site = await prisma.site.findUnique({
where: {
siteUrl
}
})
if (!site) {
notFound()
}
return (
<html lang="es">
<body>
{children}
</body>
</html>
)
}
I have multiple issues here, but the main issue is that I can't access the siteUrl
variable. Any suggestions?
1 Answer
Reset to default 0try this
const { siteUrl } = useParams<{ name: string }>()
or just remove the Promise from params type definition
params: { siteUrl: string }
layout.tsx
inside[siteUrl]
folder instead, then you can accessparams
object correctly and do the fetching, it would work exactly like the one you want to achieve by this. You can't access the params of a dynamic route that is a level or more below. – HairyHandKerchief23 Commented Feb 5 at 16:16