I am trying to add a product to the cart with shopify fetch api. I have created this code, but I can not add the product to the cart. any help please?
let submitButton = document.getElementById('submit');
let variantId = submitButton.getAttribute('data-variant-id');
let newVariantIdArray = variantId.split(',');
let product_data = newVariantIdArray.map(variantId => {
return {quantity: 1, id: variantId}
})
let data = {
items: product_data
}
function addToCart(data) {
const cartData = data
fetch('/cart/add.js', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(cartData),
})
.then((response) => {
if (response.ok) {
}
})
.catch((error) => console.error(error))
}
submitButton.addEventListener('click', (event) => {
event.preventDefault()
addToCart(variantId)
})
console.log(data)