I am stuck due to the following error : Warning: Each child in a list should have a unique "key" prop.
I have in my code :
const [watchnfts, setwatchNfts] = useState([])
......
const items = await Promise.all(data.map(async i => {
let item = {
key : i.tokenId.toNumber(),
tokenId : i.tokenId.toNumber(),
tokenURI : i.tokenURI,
watch_Model : i.watch_Model,
watch_serialnumber : i.watch_serialnumber,
brand :i._brand,
mintedBy : i.mintedBy,
currentOwner : i.currentOwner,
previousOwner : i.previousOwner,
price : i.price.toNumber(),
numberOfTransfers : i.numberOfTransfers,
forSale : i.forSale,
destroyed :i.destroyed,
accountAddress : signer.getAddress(),
}
return item
}))
console.log('items: ', items)
setwatchNfts(items)
and I get the error when I try to use that :
<MDBCardGroup>
<MDBRow>
{watchnfts.map((watch) => {
return ( <></>
/* <MyWatchNFTCard
watch={watch}
/>*/
);
})}
</MDBRow>
</MDBCardGroup>
I understood I hould set a key value but i do not understand nor how, nor where Can someone help ?
Thanks
CodePudding user response:
As suggested add any key to MyWatchNFTCard
<MDBCardGroup>
<MDBRow>
{watchnfts.map((watch) => {
return <MyWatchNFTCard watch={watch} key={watch.id} />;
})}
</MDBRow>
</MDBCardGroup>
CodePudding user response:
Keys help React identify which items have changed, are added, or are removed. Keys should be given to the elements inside the array to give the elements a stable identity.
For keys, You should use Your own unique identifier (id).
watchnfts.map((watch) => {
return (
<MyWatchNFTCard watch={watch} key={watch.id} />
)
});
When you don’t have stable IDs for rendered items, You may use the item index as a key as a last resort:
watchnfts.map((watch, index) => {
return (
<MyWatchNFTCard watch={watch} key={index} />
)
});
In other cases, such as: you want to have side-by-side elements, You can wrap them with React.Fragment
:
watchnfts.map((watch) => {
return (
<React.Fragment key={item.id}>
<MyWatchNFTCard watch={watch} />
<SomethingElse />
</React.Fragment>
)
});