Next.js Discord

Discord Forum

GET request

Unanswered
Argente Brun posted this in #help-forum
Open in Discord
Argente BrunOP
I don't understand what is wrong in my code.
Can u explain me how to handle get requests in next.js using app router

export const GET = async (id?: number) => {
    try {
        const res = await fetch(
            `https://impilomedicalsystems.co.za/wp-json/wp/v2/product`
        );

        if (!res.ok) {
            // This will activate the closest `error.js` Error Boundary
            throw new Error("Failed to fetch data");
        }

        const products = await res.json();

        if (id) {
            const product = products.find((item: any) => item.id === id);
            return product;
        }

        return products;
    } catch (error: any) {
        throw new Error(error.message);
    }
};


error:
Type error: Type '{ __tag__: "GET"; __param_position__: "first"; __param_type__: number | undefined; }' does not satisfy the constraint 'ParamCheck<Request | NextRequest>'.
  Types of property '__param_type__' are incompatible.
    Type 'number | undefined' is not assignable to type 'Request | NextRequest'.
      Type 'undefined' is not assignable to type 'Request | NextRequest'.

  31 |     Diff<
  32 |       ParamCheck<Request | NextRequest>,
> 33 |       {
     |       ^
  34 |         __tag__: 'GET'
  35 |         __param_position__: 'first'
  36 |         __param_type__: FirstArg<MaybeField<TEntry, 'GET'>>

4 Replies

you need to read the docs. id isnt a param of a get request
Argente BrunOP
I read the docs. I changed code. But I still don't understand why it's not working
import { NextRequest, NextResponse } from "next/server";

export async function GET(req?: NextRequest, res?: NextResponse) {
    try {
        const res = await fetch(
            `https://impilomedicalsystems.co.za/wp-json/wp/v2/product`,
            {
                headers: {
                    "Content-type": "application/json",
                },
            }
        );

        if (!res.ok) {
            // This will activate the closest `error.js` Error Boundary
            throw new Error("Failed to fetch data");
        }

        const products = await res.json();
        console.log(req);

        if (req) {
            const product = products.find((item: any) => item.id === req);
            return NextResponse.json({ product });
        }

        const resp = NextResponse.json({ products });
        console.log(resp);

        // return NextResponse.json({ products: products });
        return products;
    } catch (error: any) {
        throw new Error(error.message);
    }
}


error:
Warning: Only plain objects can be passed to Client Components from Server Components. Response objects are not supported.
  <... product={Response}>
I'm new at Next