0

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.

https://codesandbox.io/s/pokedex-5j1jf?file=/src/App.js

1 Answer 1

3

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()}>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.