How to trigger data fetch on button click
Say I had 3 buttons in a UI a green one, a blue one, and a red one.
- When I click the green one, I want to fetch data for 'Bulbasaur' from the pokemon api.
- When I click the blue one, I want to fetch data for 'Squirtle' from the pokemon api.
- When I click the red one, I want to fetch data for 'Charmander' from the pokemon api.
I don't think it's possible to do this with useQuery, but using useMutation feels wrong since we're not mutating data.
How would you go about this?
4 Replies
correct-apricot•11mo ago
TanStack | High Quality Open-Source Software for Web Developers
Headless, type-safe, powerful utilities for complex workflows like Data Management, Data Visualization, Charts, Tables, and UI Components.

vicious-gold•11mo ago
What about this?
optimistic-gold•11mo ago
If you want to fetch data and do something with it inside a function like maybe parse it and then send it in a mutation etc then its better to use
ensureQueryData
. Otherwise do what @andredewaard has told.fair-rose•11mo ago
this is exactly the way to go, and also what's described in the docs for "lazy queries": https://tanstack.com/query/latest/docs/framework/react/guides/disabling-queries#lazy-queries
TanStack | High Quality Open-Source Software for Web Developers
Headless, type-safe, powerful utilities for complex workflows like Data Management, Data Visualization, Charts, Tables, and UI Components.
