Reputation: 1161
In my next.js 13 app, I'm trying to fetch each blog data from local MySQL database, so in src/blog/[id]/page.js
I have this component:
const BlogPost = async ({ params }) => {
const data = await getData(params.id);
async function getData(id) {
const res = await fetch(`/api/posts/${id}`,
{next: {
revalidate: 10
}})
if (!res.ok) {
throw new Error('Failed to fetch data')
}
return res.json()
}
Where data is fetched in src/app/api/posts/[id]/route.js
:
export const GET = async (request, {params}) => {
const {id} = params
console.log('id to fetch is:', id)
const post = await query({
query:'SELECT * FROM posts WHERE `id` = ?',
values:[id],
})
console.log('post is :', post)
return NextResponse.json(post);
}
But the component does not reach this route above and I get this error instead:
error TypeError: Failed to parse URL from /posts/1
The strange thing is that I don't have any issues fetching /api/posts
in Blog
component.
I'm wondering what is wrong here and how can I fix it?
Upvotes: 0
Views: 1652
Reputation: 1161
After having a closer look, I found the essential error is
- error TypeError: Cannot destructure property 'id' of 'params' as it is undefined.
So adding `request to the GET function solved the problem:
export const GET = async (request, {params}) => {
const {id} = params
const post = await query({
query:'SELECT * FROM posts WHERE `id` = ?',
values:[id],
})
return NextResponse.json(post);
}
Upvotes: 0