I am mapping cards from an array in divs using the map() function, and I am trying to have each div include a button that will make a post request to an api. Each card in the array has a card id, which I am able to display when creating the divs using “card.id”. When I press the button, however, the addToCollection2 function is telling me that “card.id” is undefined. Can anyone tell me why it is said to be undefined?
Here is the html code:
<div className="cardImages">
{cardsFetched ? (
cards.data.map((card) => (
<div className="searchedCards" key={card.id}>
<div className="singleCard">
<img src={card.images.small} />
<p>Card ID : {card.id}</p>
<button onClick={() => addToCollection2(card.id)}>
Add Card
</button>
</div>
</div>
))
) : (
<div>Searched cards will appear below</div>
)}
</div>
Here is the addToCollection2() JavaScript function:
async function addToCollection2(cardId) {
//e.preventDefault;
console.log(cardId);
try {
const body = { collection_id, cardId };
const response = await fetch("https://tcgdex.herokuapp.com/collection", {
mode: "cors",
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(body),
});
console.log(response);
} catch (err) {
console.error(err.message);
}
return false;
}