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
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
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?
The component is built wrong 🙂
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
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