Conditional trpc hook query

When calling a trpc hook, is there a way to only make it call, if the input is validated client side? Im using zod on server side. But sometimes it takes some time on client side before the data is valid. Example:
const {
data, isLoading, isError
} = reactApi.swap.getQuote.useQuery({
fromToken: debouncedInputToken,
toToken: debouncedOutputToken,
amount: parsedInput
})
const {
data, isLoading, isError
} = reactApi.swap.getQuote.useQuery({
fromToken: debouncedInputToken,
toToken: debouncedOutputToken,
amount: parsedInput
})
In this case im using debounced values. This results in a bunch of bad type zod errors before the values are correct. And conditionally rendering hooks gives errors. So how to only conditionally fetch trpc?
3 Replies
Neto
Neto2y ago
You have a enabled property to "hold" the query until it's valid It's the second possible object of the query
andersgee
andersgee2y ago
Something like this perhaps? It would only fire the query if parsedInput is a number that is greater than 5 for example
const someSchema = z.object({ amount: z.number().gt(5) })

//...

const {
data, isLoading, isError
} = reactApi.swap.getQuote.useQuery({
fromToken: debouncedInputToken,
toToken: debouncedOutputToken,
amount: parsedInput
}, {
enabled: someSchema.safeParse({amount:parsedInput}).success
}
)
const someSchema = z.object({ amount: z.number().gt(5) })

//...

const {
data, isLoading, isError
} = reactApi.swap.getQuote.useQuery({
fromToken: debouncedInputToken,
toToken: debouncedOutputToken,
amount: parsedInput
}, {
enabled: someSchema.safeParse({amount:parsedInput}).success
}
)
Gaden
GadenOP2y ago
Thank you! I will give it a try
Want results from more Discord servers?
Add your server