T
TanStack3y ago
dependent-tan

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;} />
const fetchRedirectUrlByOption = (option: string): Promise<{ url: string }> =>
fetch(`http://localhost:3000/internal/redirect/${option}`).then((response) => {
if (response.status !== 200) {
throw new Error();
}

return response.json();
});
const fetchRedirectUrlByOption = (option: string): Promise<{ url: string }> =>
fetch(`http://localhost:3000/internal/redirect/${option}`).then((response) => {
if (response.status !== 200) {
throw new Error();
}

return response.json();
});
How should I handle this using react-query?
4 Replies
harsh-harlequin
harsh-harlequin3y 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-tan
dependent-tanOP3y 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
harsh-harlequin3y 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-refetch
React Query FAQs
Answering the most frequently asked React Query questions
dependent-tan
dependent-tanOP3y 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.

Did you find this page helpful?