Search code examples
reactjsapiuse-effect

Why can I render all of the Pokémon's names using map, but get a TypeError trying to render one name by itself?


function Shop() {

    const [pokemonData, setPokemonData] = useState([]);
    
   
    useEffect(() => {
        fetchPokemonData();
    }, []);

    const fetchPokemonData = async() => {
        const data = await fetch('https://pokeapi.co/api/v2/pokemon?limit=151');
        const pokemonData = await data.json();
        setPokemonData(pokemonData.results);
        -- pokemonData.results == [{name: 'bulbasaur'}, {name: 'squirtle'}, {name: 'charmander'}];
    };

    return (
        <div>
          
            {pokemonData[0].name}  
            {/* TypeError: Cannot read property 'name' of undefined */}

            {pokemonData.map((pokemon) => {
                return (
                    <div>
                        {pokemon.name}
                    </div>
                )
            })} 
            {/* runs with no problems */}

        </div>
    )
}

I'm not sure how to ask this question, and I've been stuck on it since yesterday. I hope I've asked my question in a coherent way. Thank you for your help and not destroying me.


Solution

  • {pokemonData.map((pokemon) => {
           return (
              <div>
                  {pokemon.name}
               </div>
             )
    })} 
    

    This code works fine because by default pokemonData state is an empty array and your using map which is an array method but when you do

    {pokemonData[0].name}
    

    you are trying to access name property inside the first object which doesn't exists until the request is completed and state is updated and this is causing the issue. You can fix this by doing

    {pokemonData.length ? pokemonData[0].name : null}