Next.js Discord

Discord Forum

TypeError: Cannot read properties of undefined (reading '0')

Answered
Pembroke Welsh Corgi posted this in #help-forum
Open in Discord
Pembroke Welsh CorgiOP
I get TypeError: Cannot read properties of undefined (reading '0') when I'm trying to access products/[slug]/page.tsx. this is products/[slug]/page.tsx
export interface ProductType {
  id: string;
  name: string;
  price: number;
  rating: number;
  slug: string;
  description: string;
  product:string;
  images: {
    id: string;
    file: {
      url: string;
      metadata: string;
    };
  }[];
}
export interface ProductProps {
  product: ProductType 
}
async function fetchProductBySlug(): Promise<ProductType> { 
  const response = await fetch(`http://localhost:3000/api/products`);

  if (!response.ok) {
    throw new Error('Failed to fetch product');
  }
  return response.json();
}
0
const Page = async ({ }: { params: { slug: string } }) => {
  const product = await fetchProductBySlug();

  return ( 
    <main>
      <Product product={product} />
    </main>
  );
};
export default Page;
and this is /components/Product.tsx where I get the error I guess is an issue with product.images[0]
const [selectedImage, setSelectedImage] = useState(product.images[0])

I guess is an issue with product.images[0]
Answered by LuisLl
const Page = async ({params}: { params: Promise<{ slug : string }> }) => {
  const { slug } = await params;
  const product = await fetchProductBySlug(slug);
//...

Aren't you supposed to pass the slug to the fetchProductBySlug() function? Also, params is a promise in Next15
View full answer

13 Replies

const Page = async ({params}: { params: Promise<{ slug : string }> }) => {
  const { slug } = await params;
  const product = await fetchProductBySlug(slug);
//...

Aren't you supposed to pass the slug to the fetchProductBySlug() function? Also, params is a promise in Next15
Answer
Pembroke Welsh CorgiOP
oh yeah i omitted that
Pembroke Welsh CorgiOP
interface PageProps { params: { slug: string }; } const getProductBySlugOrId = async (slug: string) => { const response = await fetch(http://localhost:3000/api/products/${slug}`);
if (!response.ok) throw new Error("Product not found");

return response.json();
};

const Page = async ({ params }: PageProps) => {
const product = await getProductBySlugOrId(params.slug);

return <Product product={product} />;
};

export default Page;`
i have error product not find
What Next.js version you’re using?
Pembroke Welsh CorgiOP
15.1.6
interface
PageProps {
    params: Promise<{ slug : string }>;
} 
Params are a promise now and they need to be awaited when you read them.
Pembroke Welsh CorgiOP
I'm getting this error now SyntaxError: Unexpected token '<', "<!DOCTYPE "... is not valid JSON, that means its returning html instead json, right?
interface PageProps {
    params: Promise<{ slug : string }>;
} 

const getProductBySlugOrId = async (slug: string) => {
  const response = await fetch(`http://localhost:3000/api/products/${slug}`);

  return response.json();
};

const Page = async ({ params }: PageProps) => {
  const resolvedParams = await params; 
  const product = await getProductBySlugOrId(resolvedParams.slug);

  return <Product product={product} />;
};

export default Page;
Pembroke Welsh CorgiOP
my api in the /api/products/[slug]/route.ts is
interface Params {
  slug: string;
}

export async function GET(req: Request, { params }: { params: Params }) {
  try {
    await dbConnect();

    const { slug } = params; 

    const product = await Product.findOne({ slug });

    if (!product) {
      return NextResponse.json({ message: 'Product not found' }, { status: 404 });
    }

    return NextResponse.json(product);
  } catch (error) {
    console.error('Error fetching product:', error);
    return NextResponse.json(
      { message: 'Failed to fetch product' },
      { status: 500 }
    );
  }
}
do you think is any problem with this?
Pembroke Welsh CorgiOP
Solved it!!
@Pembroke Welsh Corgi Solved it!!
I guess you had to type correctly the params in your Route Handlers as well

params: Promise<{ slug : string }>