Docs
Query
Single Query with Params

Single Query with Params

Sometimes we need to fetch data with some parameters. We want the parameters to be dynamic. Every parameters combination might resolve to a different response, and each of them should store a different state.

For example, we have a pokemon detail endpoint that accept a pokemon name. We need a query state for each pokemon name. There should be a possibility where the "charmander" pokemon query is still fetching, the "squirtle" pokemon query data has been fetched, and the "bulbasaur" pokemon query needs to be reset.

To achieve this, we use store key like what we have learned before. The query function will receive the store key as its parameter.

type Pokemon = { id: string; name: string; weight: number };
const usePokemonQuery = createQuery<{ pokemon: string }, Pokemon>(
  async ({ pokemon }) => {
    //     ^store key
    const res = await fetch(`https://pokeapi.co/api/v2/pokemon/${pokemon}`);
    if (res.ok) return res.json();
    throw res;
  }
);
 
function PokemonsPage() {
  const [currentPokemon, setCurrentPokemon] = useState();
  const { isSuccess, data } = usePokemonQuery({ pokemon: currentPokemon });
  //                                            ^store key
 
  return (
    <main>
      {isSuccess ? (
        <section>
          <h1>{data.name}</h1>
          <div>Weight: {data.weight}</div>
        </section>
      ) : (
        <div>Loading...</div>
      )}
 
      <PokemonList onSelectPokemon={setCurrentPokemon}>
    </main>
  );
}

Get data or do something outside component:

const getDitto = () => {
  console.log(usePokemonQuery.get({ pokemon: 'ditto' }).data);
  //                                ^store key
};
 
const resetDitto = () => {
  usePokemonQuery.get({ pokemon: 'ditto' }).reset();
};