2

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?
        }
    });

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.
        },
      });
    }),

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.

antonwilhelm
  • 5,768
  • 4
  • 19
  • 45
  • I think your question is partly a duplicate of https://stackoverflow.com/questions/60866714/how-can-i-specify-optional-query-filters-in-prisma -- I point that out as it had some interesting details that I found helpful while wondering about roughly the same problem (so you and others that end up here might find it useful too). – Cymen Nov 04 '22 at 23:55

1 Answers1

0

It refers to an optional properties adding to an object. Try something like this

        filters: {
          ...(colorFilter && { color: colorFilter } // filters object will be empty, if colorFilter is falsy
         }
tykhan
  • 81
  • 8