useQuery in an eventHandler?
Is it possible to put useQuery in a click handler? Say I have a field that allows user to select a number, then I want to useQuery to fetch a custom query I wrote that queries the DB for a task with that number ID, whenever I do this I'm getting a react hooks issue about hooks can only be called in the body of a function component.
My component is a function component, not sure what is going on but it seems to be related to the useQuery call as when I remove it the error goes away. I'd like to also use it to set state with reacts useState, but not sure how to manage that either.
3 Replies
Now I am able to get it working without using useQuery, and just calling the query itself. The query is returning a promise so I'm just using a .then to access the resolved promise and use in setState hook and it's working, however curious if I'm loosing any major functionality/security by not using the useQuery functionality WASP provides
Hey @nickjantz, you did it right!
The errors you were getting were -
useQuery
is a hook, which means it's mean to be called within a component and never conditionally or in a callback. The use case you want does not need (and shouldn't use a hook).
This is not really Wasp specific, it's related to React's rules and uses of hooks. I suggest reading the React docs to understand what hooks are and how to use them: https://react.dev/learn#using-hooksThis is a good question -> you are not using anything serious, but it is possible that you might be able to rewrite this to with use
useQuery
hook -> for example, instead of calling query direclty on the click, you might consider updating some state instead, and then having useQuery
call at the start of the React component that uses that state. But as @Filip said, this is not Wasp-specific, but rather comes down to how to use react hooks and best practices around that.