I am already using Redux toolkit for a while, but Im just new to the RTK query. Really enjoy it. But when I want to use the query hook, i sometimes dont want to immediately call the hook with parameters, but want to wait to call the hook after a user has entered a parameters (in the example below the variable 'bulbasaur' is just not yet known for me.
How can I do this using RTK query?
In the examples on internet and on their own website I cannot find a example? So, I dont want to call the useGetPokemonByNameQuery
immediately with the variable 'bulbasaur'
. But I want that the user first to enters a name and then call the useGetPokemonByNameQuery
with that variable.
It seems such a straightforward question... but I cannot figure out how to do this.
Code below is an example from their website.
Import * as React from 'react'
import { useGetPokemonByNameQuery } from './services/pokemon'
export default function App() {
// Using a query hook automatically fetches data and returns query values
// SO: I dont want to call the useGetPokemonByNameQuery immediately with the variable 'bulbasaur', but after the user enters a name.
const { data, error, isLoading } = useGetPokemonByNameQuery('bulbasaur')
// Individual hooks are also accessible under the generated endpoints:
// const { data, error, isLoading } = pokemonApi.endpoints.getPokemonByName.useQuery('bulbasaur')
return (
<div className="App">
{error ? (
<>Oh no, there was an error</>
) : isLoading ? (
<>Loading...</>
) : data ? (
<>
<h3>{data.species.name}</h3>
<img src={data.sprites.front_shiny} alt={data.species.name} />
</>
) : null}
</div>
)
}
For people who are still interested: use the useLazyQuery
hook (link).
This can be called any time.