问题
I am trying to permanently remove product items from my cart, but the function i created only only removes the data from the DOM and upon browser resfresh, reappears. Here is what i have done so far.
HTML with JS click function in the cart.liquid file
<a @click="removeFromCart(item)" class="product-remove">remove</a>
removeFromCart function in my CartForm.js file
removeFromCart(item){
let productInfo = this.cart.items.reduce(
(accumulator, target) => ({ ...accumulator, [target.variant_id]: target.quantity}),
{});
const myJSON = JSON.stringify(productInfo);
axios.post('/cart/update.js', { updates: productInfo })
.then((res) => {
this.cart.items.splice(this.cart.items.indexOf(productInfo), 1);
})
.catch((error) => {
new Noty({
type: 'error',
timeout: 3000,
layout: 'topRight',
text: 'Cart not updated'
}).show();
})
},
Any advice would be great. Thanks
回答1:
Shopify's Ajax API reference might help shed some light on why this isn't working for you.
If you need a working snippet of code to get things moving, this is working for me:
function removeCartItem(variantId) {
let update = {};
update[variantId] = quantity;
axios({
method: 'post',
url: '/cart/update.js',
data: { updates: update }
})
.then( (response) => {
// The response should confirm the removal of the item from cart.items
// Then you probably want to update your state so cart items gets re-rendered
})
.catch( (error) => {
console.error('Error:', error);
});
}
来源:https://stackoverflow.com/questions/65301482/shopify-cart-update-not-working-with-axios