I'm trying to show some data in my React component, but there's some data I cannot get.
I can get any other simple data, but I'm having problems to get the data inside an array.
The API format is the following:
res.data
genres: (3) [(...), (...), (...)]
0: {name: 'Adventure'}
1: {name: 'Fantasy'}
1: {name: 'Sci-Fi'}
And this is my code:
const [anime, setAnime] = useState([])
const [random, setRandom] = useState(0)
useEffect(() => {
axios
.get(`https://api.jikan.moe/v3/anime/${random}`)
.then(res => {
console.log(res.data)
setAnime(res.data)
})
.catch(err => {
randomAnime()
})
}, [random])
const randomAnime = () => {
setRandom(1 Math.floor(Math.random() * 100))
}
return (
<Anime title={anime.title} genres={anime.genres} />
)
}
Then, I pass anime.genres as props to another component. There, I try to render the following:
genres.map((genre) =>
<span key={genre.name.toString()}>
{genre.name}
</span>
)
And this error shows:
TypeError: Cannot read properties of undefined (reading 'map')
In reality, what I want to render is the following string (this part is not implemented yet, i want to merge all array items in one string separated by commas): Adventure, Fantasy, Sci-Fi.
Hope someone can help me, I've been struck all noon. Thanks in advance.
Regards
CodePudding user response:
You can prevent this by checking if genres is not undefined before trying to map it.
Something like this:
{
genres !== undefined &&
genres.map((genre) =>
<span key={genre.name.toString()}>
{genre.name}
</span>
)
}
If you want to show the items in the array with a , and display them as a string, you could use the join() method.
CodePudding user response:
You can prevent this by adding default data for gener in props. Also if "gener.name" already a string, don't need to use .toString() for key, just put gener.name is enough If you need new array only with string items, just create him like a: const newArray = genres.map(g=> g.name)