T
TanStack11mo ago
vicious-gold

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
correct-apricot11mo 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
vicious-gold
vicious-gold11mo 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>
</>
)
optimistic-gold
optimistic-gold11mo 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
fair-rose11mo 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?