NextJS Error: Cannot read properties of null (sanity)

121 views Asked by At

I am generating a store project, but I have the following problem when generating the [product] page with the slug, it shows me an Error: Cannot read properties of null (reading 'name')

app\product[productId]\page.tsx

import { getProduct } from "@/sanity/sanity-utils";

type Props = {
    params: { product: string }
  }
  
  export default async function Product({ params }: Props) {
    const slug = params.product;
    const product = await getProduct(slug);
    return <div>{product.name}</div>

  }

sanity\sanity-utils.ts

export async function getProduct(slug: string): Promise<Product> {
    return createClient(clientConfig).fetch(
        groq`*[_type == "project" && slug.current == "${slug}"][0]{
            _id,
            createdAt,
            name,
            "slug": slug.current,
            brand,
            "image": image[].asset->url,
            pack,
            sku,
            sizes,
            description,
            "category": category->name,
            "subcategory": subcategory->name
          }`,
          `{slug}`
          
        )
      }

on the sanity-utils page, if I remove the `` from the {slug} it shows me the error Error: Unable to parse value of "$slug=undefined". Please quote string values. but it didn't solve anything, it just gave me the error described above.

Please help, thank you all very much in advance!!!

2

There are 2 answers

1
jtk5th On

Replace the product param in the props type with productId, to bring it in line with your defined route.

0
Joseph Gift On

I also ran into the same issue but I finally figured it out. First of all remove the backticks from the slug object. i.e { slug }. Second, now because you have named your dynamic route [productId], that is how it should be named in the params. i.e

type Props = {
  params: { productId: string }
}

Try this code:

app\product[productId]\page.tsx // see the name [productId]

import { getProduct } from "@/sanity/sanity-utils";

type Props = {
  params: { productId: string }
}

export default async function Product({ params }: Props) {
  const slug = params.productId;
  const productId = await getProduct(slug);
  return <div>{productId.name}</div>

}

sanity\sanity-utils.ts

export async function getProduct(slug: string): Promise<Product> {
return createClient(clientConfig).fetch(
    groq`*[_type == "project" && slug.current == "${slug}"][0]{
        _id,
        createdAt,
        name,
        "slug": slug.current,
        brand,
        "image": image[].asset->url,
        pack,
        sku,
        sizes,
        description,
        "category": category->name,
        "subcategory": subcategory->name
      }`, {slug}
      
    )
  }

Tell me how it goes, thank you.