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 = () => {
JavaScript
x
32
32
1
const [post, setPost] = useState(null);
2
const [error,setError] = useState(null);
3
const [showTypes,setShowTypes]=useState(false);
4
const [showAbilities,setShowAbilities]=useState(false);
5
6
useEffect(() => {
7
instance.get("bulbasaur/").then((response) => {
8
setPost(response.data);
9
}).catch(error => {
10
setError(error);
11
})
12
},[]);
13
console.log(post);
14
if (error) return `Error: ${error.message}`;
15
if (!post) return 'no post!'
16
17
18
19
return (
20
<>
21
<h1>{post.name}</h1>
22
<button onClick={()=>setShowTypes(!showTypes)}>types</button>
23
{showTypes? <p>{(post.types[0].type.name)}</p>:null}
24
{showTypes? <p>{(post.types[1].type.name)}</p>:null}
25
<button onClick={()=>setShowAbilities(!showAbilities)}>abilities</button>
26
{showAbilities? <p>{(post.abilities[0].ability.name)}</p>:null}
27
{showAbilities? <p>{(post.abilities[1].ability.name)}</p>:null}
28
{/* <button onClick={gameVersion}>game versions</button> */}
29
{post.game_indices.version.name.map(name => <p key={post.game_indices.version.name}>{name}</p>)}
30
</>
31
)
32
}
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
JavaScript
1
2
1
{post.game_indices.map((index, idx) => <p key={idx}>{index.version.name}</p>)}
2