Currently, I am developing an e-commerce application using next.js with Typescript and MongoDB. To better understand my project, let's take a look at my existing file structure:
https://i.stack.imgur.com/tZqVm.png
The mainPage.tsx file is responsible for rendering all products in card format. By utilizing products.map and Link, each product is linked to its respective product page as shown below:
{products.map((product: ProductModel) => (
<Link
key={product._id.toString()}
href={{
pathname: "/product",
query: {
id: `${product._id.toString()}`,
},
}}
>
<CategoryCard product={product} />
</Link>
))}
In the product/page.tsx file, I extract the id from searchParams and establish that it functions correctly up to this point. However, during the product fetching process here:
const { product } = await getProduct(searchParams.id);
An error occurs displaying "Error fetching product details of product id {searchParams.id}" on the page. Below is a snippet of the file:
const getProduct = async (id: string) => {
try {
const res = await fetch(
`http://localhost:3000/api/singleproduct?id=${id}`,
{
cache: "no-cache",
}
);
if (!res.ok) {
throw new Error(`Failed to fetch product with id ${id}`);
}
return res.json();
} catch (err) {
console.error("Error fetching product:", err);
throw err;
}
};
const ProductPage = async ({
searchParams,
}: {
searchParams: { id: string };
}) => {
console.log("This is the id: ", searchParams.id);
try {
const { product } = await getProduct(searchParams.id);
return <div>This is a {product.product_title}</div>;
} catch (error) {
console.error("Error fetching product:", error);
return (
<div>Error fetching product details of product id {searchParams.id}</div>
);
}
};
export default ProductPage;
The issue possibly originates from the api/singleproduct/route.tsx file. Let's examine the code snippet:
import Product from "../../models/Product";
import { NextResponse } from "next/server";
import { NextApiRequest, NextApiResponse } from "next";
export async function GET(req: NextApiRequest, res: NextApiResponse) {
console.log("Query parameters:", req.query);
const id = req.query.id as string;
console.log("this is the id:", id);
try {
if (!id) {
throw new Error("ID parameter is missing.");
}
console.log("This is the id:", id);
const product = await Product.findById(id);
if (!product) {
return NextResponse.json({ error: "Product not found" }, { status: 404 });
}
console.log("Product from MongoDB:", product);
return NextResponse.json({ product }, { status: 200 });
} catch (error) {
console.log("Something broke:", error);
return NextResponse.json({ message: "GET request failed.", error });
}
}
Upon analysis, the console outputs "Query parameters: undefined" along with the error "TypeError: Cannot read properties of undefined (reading 'id')". How can I resolve this issue? Your guidance is greatly appreciated.