T
TanStack•2y ago
other-emerald

Call a useQuery hook only onClick and not when Component loads for the fist time

I would like to know your opinion about the solution I implemented in React. I need to call a hook that uses internally useQuery only when I click a button. What I did was to declare the hook on the component and set enable: false. With that, I avoid the first call. After that, I get the refetch property from the useQuery hook and I call it when the button clicks. I've seen that you can also use invalidateQuery, but I don't really know what would be the best option. Any other ideas? Is that a good approach? Code: const { refetch, } = useExport({ enable: false, }); const handleExport = async () => { await refetch(); };
7 Replies
other-emerald
other-emeraldOP•2y ago
@TkDodo 🔮 maybe you have an idea on this one?
exotic-emerald
exotic-emerald•2y ago
from my experience, using refetch in the onClick is the best way to achieve that
other-emerald
other-emeraldOP•2y ago
The issue is, that if I want to pass parameters to it, I can't. Would useMutation be a good alternative?
ratty-blush
ratty-blush•2y ago
really depends on what you're doing
other-emerald
other-emeraldOP•2y ago
I am clicking a button that starts a background process. It's not expected any result.
ratty-blush
ratty-blush•2y ago
that sounds like a mutation because you can't just start that "at will"
other-emerald
other-emeraldOP•2y ago
exactly I will be changing the approach and use mutation thank you all for the messages!

Did you find this page helpful?