Tom
Tom2y ago

is there a way to call useQuery() from a callback and get the return value within that callback?

I have a generic component that is effectively an autocomplete that fills in options from a web request. The component takes a callback which takes in the newest search string and should perform a web request to get the autocomplete options and return them. Is there a way I can call a trpc useQuery() and get the return value within this async callback? Thanks.
5 Replies
Nick
Nick2y ago
You should put the current search string into state and use the state to drive the query instead, this is the react-query way You will probably want to debounce the state slightly, but there are many examples of useDebounce hooks for this
Tom
TomOP2y ago
That’s not how the component works though. The component has denouncing built in it just needs to take an async function to fetch the data. There’s really no way to call the function and just get a result returned?
Nick
Nick2y ago
The component is built wrong 🙂
Tom
TomOP2y ago
I mean….. idk it’s kind of built like react query…. It takes an arena function and handles calling it and updating the state for you. Kind of the same idea Idk. Seems like a stretch to say it’s built wrong Biased cause I wrote it though. But it wad extensible to work with any async function
Nick
Nick2y ago
The react way is to drive UI from state, and make components either controlled or uncontrolled. It sounds like you've got an uncontrolled component which also passes its internal state upwards. It would be better to make it a controlled component and lift out the state so you can drive the query with it Handling of unhappy paths will get easier using useQuery rather than trying to query in a callback

Did you find this page helpful?