Home > Software engineering >  how to map an api into a paragraph
how to map an api into a paragraph

Time:06-27

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;

'''

CodePudding user response:

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>)}

CodePudding user response:

The error comes from the fact that you version is not an object in game_indices (it is undefined, which means maybe game_indices is an empty object or it does not contain the version key). Can you please check your post object again ?

  • Related