i was playing with an API and making a react app for data display. After sending my info (via form) for the request (via axios), i setted the state using setState method of React Hooks, but that is not working very well, this creates a rare behavior. I know i should use use Effect but i dont know how.
this is the part of the code where i set the state:
function Home() {
const [search, setSearch] = useState('')
const [visibleMsj, setVisibleMsj] = useState(false)
const [pokemon, setPokemon] = useState({})
const handleSearch = async (e) => {
e.preventDefault();
if(search === ''){
setVisibleMsj(true)
} else {
setVisibleMsj(false)
searchForPokemon()
}
};
const searchForPokemon = async () => {
const res = await getPokemon(search)
setPokemon(res)
console.log(pokemon)
}
This is the function that send the request (in another file):
import axios from "axios";
const getPokemon = async (name) => {
return await axios
.get(`https://pokeapi.co/api/v2/pokemon/${name}`)
.then(function (response) {
return response.data;
})
.catch(function (err) {
console.log(err);
});
};
export { getPokemon };
and finally, the form who executes the method in submit event:
<Form onSubmit={handleSearch} id="form">
<Form.Field>
<Form.Input
icon="search"
placeholder="Search by name or id..."
name="pokemon"
onChange={(event) => setSearch(event.target.value)}
value={search}
/>
</Form.Field>
</Form>
But in the console i get this when i send the request: Console in web browser
So, what is happening with the state?. Also, i need to display atributtes of the state variable 'pokemon' below the form (inside render) and i cant get these attributes, maybe because the first value when mounting is {}?.
Thanks in advance.