Hi I am trying to map an array of an api to display paragraphs for every index within the array. However I keep getting an error :
**> TypeError: undefined is not an object (evaluating
‘post.game_indices.version.name’)**
But when I console log post and use my buttons below it displays what I want and not undefined. So why is it undefined when I want to map the paragraphs?
”’
import React, {useEffect,useState} from ‘react’ import instance from ‘./axios’
const Home = () => {
const [post, setPost] = useState(null); const [error,setError] = useState(null); const [showTypes,setShowTypes]=useState(false); const [showAbilities,setShowAbilities]=useState(false); useEffect(() => { instance.get("bulbasaur/").then((response) => { setPost(response.data); }).catch(error => { setError(error); }) },[]); console.log(post); if (error) return `Error: ${error.message}`; if (!post) return 'no post!' return ( <> <h1>{post.name}</h1> <button onClick={()=>setShowTypes(!showTypes)}>types</button> {showTypes? <p>{(post.types[0].type.name)}</p>:null} {showTypes? <p>{(post.types[1].type.name)}</p>:null} <button onClick={()=>setShowAbilities(!showAbilities)}>abilities</button> {showAbilities? <p>{(post.abilities[0].ability.name)}</p>:null} {showAbilities? <p>{(post.abilities[1].ability.name)}</p>:null} {/* <button onClick={gameVersion}>game versions</button> */} {post.game_indices.version.name.map(name => <p key={post.game_indices.version.name}>{name}</p>)} </> )
}
export default Home;
”’
Advertisement
Answer
ok, I recreated your app and found a problem – you should map on array post.game_indices
and then display index.version.name
{post.game_indices.map((index, idx) => <p key={idx}>{index.version.name}</p>)}