Happening now | Office Hours: Customizing Your Theme With Moeed | Ask your questions now!

Adding a product to the cart and re-render from a checkbox inside the drawer

Adding a product to the cart and re-render from a checkbox inside the drawer

kifkifff
Shopify Partner
1 0 0

Hi, i have added a checkbox to the DAWN theme drawer. 
<input
type="checkbox"
id="specific-product-checkbox"
{% if specific_product_in_cart %} checked {% endif %}
onchange="handleCheckboxChange(this)"
>
The checkbox is checked or not, based on if there is an specific product on the cart. All good for now ; )

I managed to add or delete the fixed product from the cart, but the problem is trying to reload the drawer with the new info (products and prices). Right now it's not reloading and after hours i'm not sure how to proceed...

This is the complete code:

 

function handleCheckboxChange(checkbox) {
const variantID = "a fixed variant ID";
const quantity = checkbox.checked ? 1 : 0;
this.cart = document.querySelector('cart-drawer');

// Fetch the current cart data first
fetch('/cart.js')
.then(res => res.json())
.then(cart => {
fetch(quantity > 0 ? '/cart/add.js' : '/cart.js', {
method: quantity > 0 ? 'POST' : 'GET',
credentials: 'same-origin',
headers: {
'Content-Type': 'application/json',
'X-Requested-With': 'xmlhttprequest',
},
body: quantity > 0 ? JSON.stringify({
items: [{
id: variantID.toString(),
quantity: quantity
}]
}) : undefined
})
.then(async (response) => {
const responseData = await response.json();

console.log("Raw response data:", responseData.items[0]);

if (responseData.status) {
console.error('Error al agregar/eliminar el producto:', responseData.errors || responseData.description);
return;
}

// Append sections from the cart object. Here i get lost
const responseDataItem = cart.items[0];
responseDataItem.sections = cart.getSectionsToRender().map((section) => section.section);
console.log('Producto despues:', responseDataItem);

// Update the cart content
if (this.cart) {
this.cart.renderContents(cart);
}
})
.catch((error) => {
console.error('Error al actualizar el carrito:', error);
});
});
}   

 Any help would be really apreciated. Thanks in advance,

Replies 0 (0)