How should I retrieve data in a dynamic route when not using generateStaticParams
Unanswered
Plott Hound posted this in #help-forum
Plott HoundOP
Hi. My project lets users create workout routines and then initiate an exercise for them. When the user starts an exercise the route goes into [id] and I can get the id using params.
What I need help with is how to get the rest of the data associated with that id in this server component. I know I probably shouldn’t use a route handler since it’s a server component, should I just fetch it in the same file with prisma findUnique?
Edit for more info. I’m using app router with prisma
What I need help with is how to get the rest of the data associated with that id in this server component. I know I probably shouldn’t use a route handler since it’s a server component, should I just fetch it in the same file with prisma findUnique?
Edit for more info. I’m using app router with prisma
12 Replies
Giant panda
Have you read the Data Fetching chapter in the docs? It should answer your question.
Tbh, regardless of what others say I'm quite fine with using route handlers even in server components, the time delay is negligible but there might be some caveats when using static params ig.
Giant panda
It's not just about the delay. It's inconvenient and flat out doesn't work in some cases.
While also increasing costs.
Additionally you'd have to deal with proper URLs which vary A LOT in preview environments etc.
Also it's completely against the design of RSCs.
@Giant panda Have you read the Data Fetching chapter in the docs? It should answer your question.
Plott HoundOP
In this project I typically fetch in server components like this
async function fetchExercises() {
return await prisma.exercise.findMany({
select: {
id: true,
name: true,
},
take: 200,
});
}
Am I ok doing this in dynamic paths with findUnique by passing the id from params or is there a better way.
async function fetchExercises() {
return await prisma.exercise.findMany({
select: {
id: true,
name: true,
},
take: 200,
});
}
Am I ok doing this in dynamic paths with findUnique by passing the id from params or is there a better way.
Giant panda
return await is useless, but yeah that's the general approachAnd if
findUnique doesn't return a result because the ID from the path was incorrect you can either display an error component or flat out call notFound()Plott HoundOP
Thank you. I wasn’t aware return await was useless. Should I just return prisma… ?
Giant panda
Yes
Plott HoundOP
Thanks a lot for the help Near. In my previous project I was fetching from a cms and I just wanted some guidance now I’m learning CRUD best practices in app router. Thanks!