skip to Main Content

Here I write script in app/shop/[id]/page.tsx

export default function Shop({ children, sections = [] }) {
  const [shopData, setShopData] = useState(null);
  const params = useParams()
 
  // Get the id from the route
  const { id } = params;

  useEffect(() => {
    const fetchData = async () => {
      try {
        if (id) {
          const response = await fetch(`/api/shop/${id}`);
    
          if (response.ok) {
            const result = await response.json();
            setShopData(result.shop);
          } else {
            console.error('Failed to fetch shop:', response.statusText);
          }
        }
      } catch (error) {
        console.error('Error fetching shop:', error);
      }
    };

    fetchData();
  }, [id]);

I check in log console and ID is correct passed to API. Now I try retrive this ID in api:
here is code:

import { NextApiRequest, NextApiResponse } from 'next';
import prisma from '@/lib/prisma';
import { NextResponse } from 'next/server';

export async function GET(req: NextApiRequest, res: NextApiResponse): Promise<void> {
  try {

    console.log('req.query:', req.query);
 

    // Access the id parameter directly from req.query
    const id = req.query;

    if (!id) {
      return NextResponse.json({ error: 'ID parameter is missing' }, { status: 400 });
    }

    // Use Prisma to find the shop by ID
    const shop = await prisma.shop.findUnique({
      where: {
        id: Number(id),
      },
    });

    if (!shop) {
      return NextResponse.json({ error: 'Shop not found' }, { status: 404 });
    }

    // Return the shop data
    return NextResponse.json({ shop });
  } catch (error) {
    console.error('Error fetching shop by ID:', error);
    return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
  }
}

But everytime I get: ID parameter is missing

When I manual in API set id example 2 then working, So the issue is with GET/ retrive this ID.

2

Answers


  1. You are going about this the wrong way. The Shop component should really be a server component. This would allow you to discard the whole API all together:

    import prisma from '@/lib/prisma';
    
    interface Props {
      params: { id: string },
    }
    
    // file: app/shop/[id]/page.tsx
    export default async function Shop({ params }: Props) {
      const { id } = params;
    
      const shop = await prisma.shop.findUnique({
        where: { id: Number(id) },
      });
    
      if (!shop) {
        // throw a not found, render empty placeholder 
        // or redirect
      }
    
      // the rest of your component
      return <></>;
    }
    

    Generally speaking, when working with Next.js 14 you should always try to minimize the usage of client side code as much as possible.


    Furthermore, I have noticed your API definition is also invalid. We no longer receive the response object via the second function param but instead API’s are used like this:

    import { NextResponse, type NextRequest } from "next/server";
    
    export async function GET(request: NextRequest) {
      return NextResponse.json({ message: "Hello world!" });
    }
    
    Login or Signup to reply.
  2. In your component make the call to API as:

    //get a hold to id, which you mentioned you are able to...
    //call the API, passing id as parameter  
    fetchByID(id) 
          .then((response)=>{
            //do whatever needs to be done
          }).catch((error)=>{
            console.log(error);
          })
    

    In your API component:

    //define the API route
    const fetchByIDURL = "http://localhost:8080/fetch-by-ID/"; //the last '/' is needed as we will append the ID after it.
    
    export async function fetchByID(id) {
      return await axios.get(fetchByIDURL+id);
    }
    

    import this in component within curly braces as

    import {fetchByIDURL } from 'give path'
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search