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:
Can you know, how to fix it?
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