Next.js Discord

Discord Forum

can only use await in server compontents, can only get url parameters in client components

Answered
Gharial posted this in #help-forum
Open in Discord
GharialOP
I'm brand new to next.

I'm trying to do a simple content fetch from a database based on the URL.

I need to get the slug of the content from the URL, so I need to use useParams(). But apparently that's only available on the client, so I have to make my component a client component. But then I can't use await (and fetch the database info).

What are you supposed to do?

"use client";

import { useParams } from 'next/navigation';
import { fetchProductBySlug } from '../fetch-product';
import { Suspense } from 'react';
import {ProductPage} from '../product-page';

export default async function Page() {
    const urlParams = useParams();
    const slug = Array.isArray(urlParams.slug) ? urlParams.slug[0] : urlParams.slug;
    const product = await fetchProductBySlug(slug);

    if (!product) {
        return <div className="page"><h1>Product Not Found</h1></div>;
    }

    return (
        <Suspense fallback={"loading"}>
            <ProductPage product={product} />
         </Suspense>
    );
}
Answered by chisto
you can get searchParams from page as server component this way

export default function Page({
searchParams
}: {
searchParams: { [key: string]: string | string[] | undefined }
}) {

https://nextjs.org/docs/app/api-reference/file-conventions/page
View full answer

2 Replies

you can get searchParams from page as server component this way

export default function Page({
searchParams
}: {
searchParams: { [key: string]: string | string[] | undefined }
}) {

https://nextjs.org/docs/app/api-reference/file-conventions/page
Answer