Apologies in advance for any grammatical errors in my English, it's not my native language. I'm encountering difficulties in adding a product fetched from the API to my cart when clicking the button. Upon clicking, the console displays the following error:
Uncaught ReferenceError: ${product.id} is not defined at HTMLAnchorElement.onclick (VM#### index.html:1:11)
The variable ${product.id} represents the ID of the respective product.
Here is the snippet of code causing the issue:
let products = [];
// GENERATE PRODUCT CARDS
const generateCards = (arrayFiltered) => {
let generatorCards = ``;
arrayFiltered.forEach((product) => {
generatorCards += ` <div class="card-responsive col mb-5">
<div class="card h-100">
<!-- Product image-->
<img class="card-img-top" src="${product.thumbnail}" alt="..." />
<!-- Product details-->
<div class="card-body p-4">
<div class="text-center">
<!-- Product name-->
<h5 class="fw-bolder">${product.title}</h5>
<!-- Product price-->
$${product.price}
</div>
</div>
<!-- Product actions-->
<div class="card-footer p-4 pt-0 border-top-0 bg-transparent">
<div class="text-center"><a class="btn btn-outline-dark mt-auto mb-2 btn_add-cart" href="#" onclick="addToCart(${product.id})">Add to Cart</a></div>
</div>
</div>
</div>`;
})
document.getElementById('container-products').innerHTML = generatorCards;
};
// ADD TO CART FUNCTION
const addToCart = (productId) => {
const foundIndex = products.findIndex(product => product.id == productId);
cart.push(products[foundIndex]);
Toastify({
text: "Product successfully added to cart! :D",
duration: 2500,
}).showToast();
cartReduce();
};
// FETCH DATA
API_URL = 'https://api.mercadolibre.com'
API_ENDPOINT_SEARCH_NICKNAME = '/sites/MLA/search?nickname='
const fetchDataBase = () => {
fetch(API_URL + API_ENDPOINT_SEARCH_NICKNAME + 'FVENTAS+ONCE')
.then((response) => response.json())
.then((data) => {
products = products.concat(data.results);
console.log(data);
generateCards(products);
})
}
fetchDataBase();
<section>
<div class="container px-4 px-lg-5 mt-5">
<div id="container-products"
class="row gx-4 gx-lg-5 row-cols-1 row-cols-md-2 row-cols-lg-3 row-cols-xl-4 justify-content-center">
</div>
</div>
</section>
HELP NEEDED URGENTLY FOR MY FINAL JAVASCRIPT PROJECT! Thank you so much in advance!
If you want to check out the live page to better understand my issue, here is the link to the GitHub page: