Today, i come up with one problem that i'm using Next js 13.4 version with backend. so when i used searchParams in server side, it was throwing error: Cannot read properties of undefined (reading 'size') iam destructuring size and style search params. this is my code:
Iam performing add to cart functionlaity, which speaks to backend. this is my addToCart function:
const addToCartHandler = async () => {
const style = Number(searchParams.get("style"));
const size = searchParams.get("size");
console.log("iam from front", style, Number(size));
await axios
.get(`/api/product/${product._id}?style=${style}&size=${size}`)
.then((res) => console.log("data------>", res.data));
};
this is my product/[id]/route.ts:
import { NextResponse } from "next/server";
import connect from "../../../../utils/db";
export const GET = async (
req: Request,
{ params, searchParams }: { params: any; searchParams: any }
) => {
try {
await connect();
const { id } = params;
const size = searchParams.size;
const style = searchParams.style;
console.log(id, size, style);
return new NextResponse(id, { status: 200 });
} catch (error: any) {
return new NextResponse(`${error}`, {
status: 500,
statusText: error.message,
});
}
};
I have tried this above code after clicking add to cart button, it throws me
I think there's an error in backend. Please ignore it if you think this is stupid, it's a beginner mistake. :)
In NodeJS's world, searchParams is an object that has many methods and doesn't directly returns a value. In this case, searchParams.size
would equan an instance of URLSearchParams
object, meaning searchParams
equal to an URLSearchParams
object, and URLSearchParams.size
is undefined
.
The right way to fix it would be
const size = searchParams.get('size');
const style = searchParams.get('style');
See official NodeJS doc for searchParams
here https://nodejs.org/api/url.html#urlsearchparams