I'm currently trying to learn ReactJS and running into some issues with state and useEffect - If I take the following React code:
import './App.css';
import { useState, useEffect } from 'react';
import PokemonCard from './components/PokemonCard';
const interval = {
limit: 25
}
const App = (props) => {
const { pokedex, } = props
const [pokemonList, setPokemonList] = useState([])
useEffect(() => {
const getPokemonListData = async () => {
let pokemon = await pokedex.getPokemonsList(interval)
setPokemonList(pokemon.results)
}
getPokemonListData()
}, [])
return (
<div className="App">
<h1>Pokedecs</h1>
<div className="container">
{
pokemonList?.map(poke => {
return <PokemonCard key={poke.name} pokedex={pokedex} pokemonName={poke.name} />
})
}
</div>
</div>
);
}
export default App;
import { useEffect, useState } from "react"
import PokemonTypePill from "./PokemonTypePill"
import '../App.css';
const PokemonCard = (props) => {
let styles = {
card: {
backgroundColor: "#fff",
height: "200px",
width: "150px",
boxShadow: '1px 2px 5px #000000',
margin: "15px",
textAlign: "center",
borderRadius: "12px",
fontWeight: "bold",
transition: "transform .2s"
}
}
const {pokemonName, pokedex, } = props
const [pokemonData, setPokemonData] = useState({})
const getPokemonData = async () => {
let pokemon = await pokedex.getPokemonByName(pokemonName)
setPokemonData(pokemon)
}
const pokemonTypes = () => {
console.log(pokemonData) //this always uses the initial state "{}"
}
useEffect(() => {
getPokemonData()
pokemonTypes()
}, [setPokemonData])
return (
<div className="card" style={styles.card}>
<img src={pokemonData.sprites && pokemonData.sprites?.front_default} />
<p>#{pokemonData.id} {pokemonName.charAt(0).toUpperCase() + pokemonName.slice(1)}</p>
<div style={{width: "inherit", display: "flex", alignContent: "center", justifyContent: "center"}}>
{
pokemonData.types?.map((pokemonType) => {
return (
<PokemonTypePill key={pokemonType.type.name} typeName={pokemonType.type.name} />
)
})
}
</div>
</div>
)
}
export default PokemonCard
In the Component "PokemonCard" inside of the pokemonTypes method, on first load, the data is printed to the console with the updated state of "pokemonData". When the page is refreshed, the empty objects are printed to the console, which is the initial state. Why does the data print to the console on the initial load, but on refresh it reverts back to the initial state.