Filtering in React-Query & Trpc?

Say I have a filter on my frontend. I have an option to get all the users who are blue or all the users who are red. In the front-end, I pass that filter value into react-query and in the backend I use that passed-down filter value in my prisma call to my database. In trpc/react-query I do:
const { data, isLoading } = trpc.user.getAll.useQuery({
filters: {
color: colorFilter //when I don't have a filter, I want to (ideally) remove this line here?
}
});
const { data, isLoading } = trpc.user.getAll.useQuery({
filters: {
color: colorFilter //when I don't have a filter, I want to (ideally) remove this line here?
}
});
And then in the backend (trpc) in prisma (using mysql) I do:
getAll: t.procedure
.input(z.object({
filters: z.object({ color: z.string() })
}).nullish())
.query(({ ctx, input }) => {
return ctx.prisma.user.findMany({
where: {
color: input?.filters.color //this works when we do want to filter for a color (red/blue); but when I don't pass down a filter for either red or blue, I want this whole line to gone.
},
});
}),
getAll: t.procedure
.input(z.object({
filters: z.object({ color: z.string() })
}).nullish())
.query(({ ctx, input }) => {
return ctx.prisma.user.findMany({
where: {
color: input?.filters.color //this works when we do want to filter for a color (red/blue); but when I don't pass down a filter for either red or blue, I want this whole line to gone.
},
});
}),
What I don't understand is what I would do if I do not want to have a filter at all? When I do not want to have a filter applied, I don't want to pass down something like color: ALL, but I just want to pass down NO filter at all. But I don't understand how to make this dynamic, since right now my backend (prisma) expects this filter to be there and have some sort of value. How can I include the filter in the object when I want it / when it's passed, and how can I omit it when it isn't? Same also for the frontend. My useQuery expects a filter there now. But what when I don't want a filter? And how would I do this in a clean way? I am worried that things could go very messy when I have a lot of filters at some point.
1 Reply
cje
cje3y ago
where: {
...(input.filters.color && {color: input.filters.color})
}
where: {
...(input.filters.color && {color: input.filters.color})
}
and make it optional in the schema
Want results from more Discord servers?
Add your server