I am trying to fetch information from my mongodb server and display it using map.
<div>
<h1>Mypolls</h1>
{/* You can map through the polls array and render the poll data */}
{polls.map((poll) => (
<div key={poll.id}>
<div>{poll.question}</div>
{/* Map through options and render each option */}
{poll.options.map((option, index) => (
<div key={`${poll.id}-${index}`}>{option.text}</div>
))}
</div>
))}
</div>
Question is being displayed but options are not.
Console is showing the following error:
"Warning: Each child in a list should have a unique "key" prop."
2
Answers
It seems like you’re correctly assigning a unique key to each poll element, but the issue might be with the key for the options within each poll. The key should be unique for each element in the array, but currently, you are using the same key for each option in every poll.
To fix this issue, you can combine the poll id with the index of the option to create a unique key for each option. Update the key for options like this:
{poll.options.map((option, index) => (
<div key={
${poll.id}-${index}
}>{option.text}))}
You’ve correctly assigned a unique key to the outer element inside the first map function using key={poll.id}, but you also need to assign a unique key to each inner element inside the second map function. The error you’re seeing indicates that the inner elements inside the second map function are missing unique keys.
To fix this issue, you can use a combination of the poll id and the index of the outer map function to create unique keys for the inner elements. Here’s an updated version of your code: