How to run useQuery with the press of a button
New to react-query v4 and was wondering how i should implement the following feature, we have an endpoint that has to be called on a button press.
For example:
Button A:
<Button onClick={() => fetchRedirectUrlByOption('a').then((data) => window.location = data.url;} />
Button B: <Button onClick={() => fetchRedirectUrlByOption('b').then((data) => window.location = data.url;} />
How should I handle this using react-query?4 Replies
harsh-harlequin•3y ago
One way is to use a query being « enabled: false » and use the «refetch » function returned by the useQuery hook as button onClick.
dependent-tanOP•3y ago
https://codesandbox.io/s/thirsty-lake-yzu3cd?file=/src/App.tsx
Tried to build it in the sandbox, however, im not sure how to call refetch with a parameter.
kevinvdburgt
CodeSandbox
thirsty-lake-yzu3cd - CodeSandbox
thirsty-lake-yzu3cd by kevinvdburgt using @tanstack/react-query, react, react-dom, react-scripts
harsh-harlequin•3y ago
You can't call
refetch with parameters. Please have a look at @TkDodo 🔮 's blog => https://tkdodo.eu/blog/react-query-fa-qs#how-can-i-pass-parameters-to-refetchReact Query FAQs
Answering the most frequently asked React Query questions
dependent-tanOP•3y ago
That article does make a lot of sense for fetching data that you want to display (was also a nice read, thanks @TkDodo 🔮!). However, it feels that for my usecase i do need to write a lot of boilerplate or is there something i've been doing wrong in my updated sandbox?
https://codesandbox.io/s/thirsty-lake-yzu3cd?file=/src/App.tsx
Ive been wondering if using
useMutation is a better usage for this, it wont modify any data, only queries it. But i can call mutation.mutateAsync({provider: 'facebook'}).then(...). It just feels wrong using a useMutation for just a query where i dont mutate anything.