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
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: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:
In your component make the call to API as:
In your API component:
import this in component within curly braces as