0

I have one small question. My app do fetch request after click on card. But I have some trouble. My fetch request doing everytime, but it must doing only after click. So my fetch request looks like this:

  useEffect(() => {
    let endpointForPokemonDetails = `${API_URL}${index}`;
    fetchPokemonDetails(endpointForPokemonDetails);
  });

  const fetchPokemonDetails = (endpointForPokemonDetails) => {
    fetch(endpointForPokemonDetails)
      .then((result) => result.json())
      .then((result) => {
        setPokemon([Pokemon, result]);
      }, setLoading(false))
      .catch((error) => console.log("Error:", error));
  };

Before I click to card, I have some errors in console.log: enter image description here

Can you know, how to fix it?

3 Answers 3

1

Use onClick prop on your button (or any other HTML element):

<button type="button" onClick={() => fetchPokemonDetails(index)}>
Fetch pokemon
</button>

Also change fetchPokemonDetails to accept an index parameter:

 const fetchPokemonDetails = (index) => {
    fetch(`${API_URL}${index}`)......

useEffect is a React hook that is used to trigger side effects. See https://reactjs.org/docs/hooks-reference.html#useeffect

Sign up to request clarification or add additional context in comments.

Comments

1

By using useEffect, you tell React that your component needs to do something after render. React will remember the function you passed (we’ll refer to it as our “effect”), and call it later after performing the DOM updates

So the reason why you get the error is because you are using useEffect. This will call the API after render with index = undefined

You can remove useEffect method and call fetchPokemonDetails on onClickHandler

Comments

0

You can use only click event and so you use the function only after clicking , you should not use useEffect. useEffect had side effect .

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.