outis99
outis993y ago

Can I redirect the user from inside my router?

I have a query protectedProcedure, which returns an object from my prisma planetscale db What's the best way to redirect the user to a 404 page if the item doesn't exist on the db? I wanted something like res.redirect("/404") but can't seem to find a way to do it Should I just handle it in the front-end with a useEffect?
4 Replies
tomheaton
tomheaton3y ago
on your useQuery you can add an onError handler where you could redirect the user after raising a trpc error in your router when no item is found
outis99
outis99OP3y ago
That might actually be what I want, thank you!
outis99
outis99OP3y ago
client
const { data } = trpc.project.get.useQuery({ slug: String(router.query.slug) }, {
enabled: typeof router.query.slug === "string",
onError(err) {
console.log(err, 'error123')
//router.push("/404")
},
})
const { data } = trpc.project.get.useQuery({ slug: String(router.query.slug) }, {
enabled: typeof router.query.slug === "string",
onError(err) {
console.log(err, 'error123')
//router.push("/404")
},
})
server
get: protectedProcedure
.input(z.object({ slug: z.string() }))
.query(async ({ input, ctx }) => {
const project = await ctx.prisma.project.findFirst({
where: {
slug: input.slug,
user: {
email: ctx.session.user.email,
},
},
include: {
columns: {
include: {
cards: true,
},
},
},
});
if (!project?.id)
throw new TRPCError({ code: "NOT_FOUND", message: "eza" });
else return { project };
}),
get: protectedProcedure
.input(z.object({ slug: z.string() }))
.query(async ({ input, ctx }) => {
const project = await ctx.prisma.project.findFirst({
where: {
slug: input.slug,
user: {
email: ctx.session.user.email,
},
},
include: {
columns: {
include: {
cards: true,
},
},
},
});
if (!project?.id)
throw new TRPCError({ code: "NOT_FOUND", message: "eza" });
else return { project };
}),
outis99
outis99OP3y ago
For some reason the query executes 4 times and only executes the onError function on the 4th time, which in total takes like 5 seconds Also I'm using enabled here to conditionally execute the query when the next/router is ready, if anyone has a better implementation would love to hear it

Did you find this page helpful?