Shopify cart update not working with axios

删除回忆录丶 提交于 2020-12-27 06:16:36

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!