I'm wondering how to go about displaying some data from an API response.
The above image is the API response I'm working with. I'm able to take the name and display that, as well as the cover URL, id, and summary. However, when it comes to the genres and platforms, I'm not sure how to get into those arrays to get to the objects.
Here is how I'm assigning these values.
const gameData = result.map((game) => ({
gameId: game.id,
name: game.name,
cover: game.cover,
summary: game.summary,
platforms: game.platforms,
genres: game.genres,
}));
And here is how I'm displaying these results:
<div key={game.gameId}>
<div className='myHeader'>
<h2>
{game.name}
</h2>
</div>
<div>
<img src={'http:' game.cover.url} alt={`The cover for ${game.name}`}></img>
</div>
<div>
Genre: {game.genres.name}
</div>
</div>
This doesn't flip any errors in the console, but I am pretty certain that I'm not actually doing anything with the "genres" array in the response. I don't think it's assigned appropriately.
This post is a little light on code (I think the issue lies in what I've posted,) but if it makes a difference, the API call is within a useEffect hook. I'd be happy to add any code that would help anyone help out!
My question is, how do I destructure the array to assign the value I want?
CodePudding user response:
You're assigning the value of genres
right, the issue is with how you're accesing the values.
You're trying to access the name
key but genres
is an array.
You should map genres
and return an HTML element for each item:
{game.genres.map(genre => (<p>{genre.name}</p>) )}