1

I would like to take the output of one query (a TRPC query on Prisma) and use this as the dependent input in a future query.

I followed the dependent documentation for React Query but running into type errors that the return of the first may possibly be undefined (e.g. product is possibly 'undefined'):

  const { data: product } = api.product.getUnique.useQuery({ id: pid });

  const options = api.option.getAll.useQuery(
    {
      product: product.productSize,
      region: product.productRegion,
    },
    { enabled: !!product }
  );

Does the inclusion of enabled not already handle this? If not, what is the correct way to adapt for Typescript.

NickP
  • 1,354
  • 1
  • 21
  • 51

1 Answers1

1

Just casting the product value as a boolean return any truthy value (f.e if product will be equal to {} it will still result in true, that means that product won't necessarily have the productSize or productRegion properties, I would change it first to:

{ enabled: !!product && product.productSize && product.productRegion }

If that doesn't fix the typescript error, you as a developer can know for sure that the values are actually there so what you can use the as keyword in typescript to tell it that you know for sure that the type is what you want it to be: (In this example I assumed that the values are string but you can change it to number or whatever the true value of them are)

const options = api.option.getAll.useQuery(
    {
      product: product.productSize as string,
      region: product.productRegion as string,
    },
    { enabled: !!product && product.productSize && product.productRegion }
  );
EkkoKo
  • 214
  • 1
  • 5