I am learning React hooks and made a project to display a random Pokemon name through https://pokeapi.co/docs/v2#pokemon by calling a random Pokemon ID. I’m not quite sure how to trigger the useEffect
to fetch after clicking on the button.
import './App.css';
import { useState, useEffect } from 'react';
function getNewPokemonId(pokemon){
pokemon = Math.floor(Math.random() * 1011);
console.log(pokemon)
return pokemon;
}
function App() {
const [pokemon , setNewPokemon] = useState(1);
useEffect(() => {
console.log("render");
const pokemonID = getNewPokemonId()
fetch(`https://pokeapi.co/api/v2/pokemon/${pokemonID}`)
.then((response) => response.json())
.then((json) =>
setNewPokemon(json)
);
}, []);
return (
<main>
<h1>
Random Pokemon Generator
</h1>
<section>
<button onClick={() => setNewPokemon(getNewPokemonId(pokemon))}>
New Pokemon
</button>
<h3>{pokemon?.name}</h3>
</section>
</main>
);
}
export default App;
After clicking on the button I don’t get a new Pokemon name instead it is blank.
4
Answers
having
[]
at the end of the useEffect will mean it will only trigger once at the start of the page load.having this:
[pokemon]
will make the useEffect run every time the variable changes.You can define a function to fetch the data for a Pokemon by id and call it on mount and in the click event handler.
I created a sandbox with this app working:
Sandbox https://codesandbox.io/s/holy-morning-tkwtpv
I hope that this could help
It’ not fool-proof, but it’s a start. You should store the Pokémon data into the state, not the ID. Make sure you properly set the state as well.
Note
If you notice, the IDs jump from 1010 to 10001.
So the random range should technically be: 1-1010, 10001-10271.
Example
Here is an basic working example of a Pokémon randomizer. It’s fairly responsive.