I'm building a Pokedex (Pokemon Index) application, using React Hook Form and React Query in which a user can submit a pokemon's name and that pokemon's data will render. I'm having trouble retrieving the individual pokemon's data. When I submit a pokemon's name, I receive a status 200 for the query, but the console prints an empty object. Please let me know what I'm doing wrong.
1 Answer
useQuery hook expects a function that returns a promise. So handlePokemonFetch should look like this:
const handlePokemonFetch = () => {
return axios(`https://pokeapi.co/api/v2/pokemon/${query}`);
};
Normally react-query would run the query when the component is mounted. If you do not want this behaviour, you have to disable the query by setting, enabled: false, which you actually did. If you want to trigger a fetch by yourself react-query gives you refetch function:
//notice that we also destructure the refetch function
const { isLoading, isError, data, error, refetch } = useQuery(
"pokemon",
handlePokemonFetch,
{
refetchOnWindowFocus: false,
enabled: false
}
);
//when the data is available save it on the state
if(data) setPokemonCharacter(data);
And the you call that function when the form is submitted:
<form onSubmit={()=>refetch()}>