T
TanStack15mo ago
grumpy-cyan

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
rival-black
rival-black15mo 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.
From An unknown user
From An unknown user
fair-rose
fair-rose14mo ago
What about this?
const [pokemon, setPokemon] = useState('')

const query = useQuery({
queryKey: ['pokemon', pokemon],
queryFn: () => Promise.resolve(pokemon),
enabled: !!pokemon
})


return (
<>
<button onClick={() => setPokemon('Bulbasaur')}>Fetch Bulbasaur</button>
<button onClick={() => setPokemon('Squirtle')}>Fetch Squirtle</button>
<button onClick={() => setPokemon('Charmander')}>Fetch Charmander</button>
</>
)
const [pokemon, setPokemon] = useState('')

const query = useQuery({
queryKey: ['pokemon', pokemon],
queryFn: () => Promise.resolve(pokemon),
enabled: !!pokemon
})


return (
<>
<button onClick={() => setPokemon('Bulbasaur')}>Fetch Bulbasaur</button>
<button onClick={() => setPokemon('Squirtle')}>Fetch Squirtle</button>
<button onClick={() => setPokemon('Charmander')}>Fetch Charmander</button>
</>
)
absent-sapphire
absent-sapphire14mo 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.
correct-apricot
correct-apricot14mo 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.
From An unknown user
From An unknown user

Did you find this page helpful?