javascript - Alpine js - $dispatch from another component -> this.$dispatch is not a function
First sorry for my english! Im trying to create add to cart ajax button in Shopify with Alpine js and JS Vanilla, but when click in the button the console says this.$dispatch(the dispatchs come from another liquid files) is not a function, i think is something about the scope of the function, im new on alpine and also i didnt find doc about this. I let my code:
<div class="product--information px-4 md:px-0 md:sticky"
x-data="{
addToCart() {
let formData = new FormData(this.$refs.product_form);
fetch('/cart/add.js', {
method: 'POST',
body: formData
})
.then(response => {
return response.json();
})
.then(response => {
this.$dispatch('cart-updated');
this.$dispatch('toggle-cart');
})
.catch((error) => {
console.error('Error:', error);
});
}
}"
>
{% form 'product', product, id: 'product-form', novalidate: 'novalidate', x-ref: 'product_form' %}
<div class="flex md:w-1/2">
<button type="button" @click="addToCart()" class="flex-1 p-4 uppercase bg-black text-white text-center" {% if
selected_variant.variant.available==false %} disabled {% endif %}>
{% if selected_variant.variant.available == false %}
Sold Out
{% else %}
Add to cart
{% endif %}
</button>
</div>
Answer
Solution:
There are several bugs, even without seeing the full code, I could add the following lines of code, but it would be very helpful to add the full code of your "template-product.liquid" file.
Add below product--information this code:
{%- assign product_form_id = 'product-form-' | append: section.id -%}
like this:
<div class="product--information px-4 md:px-0 md:sticky"
{%- assign product_form_id = 'product-form-' | append: section.id -%}
and then in the end of code, change:
{% form 'product', product, id: 'product-form', novalidate: 'novalidate', x-ref: 'product_form' %}
to this:
{%- form 'product', product, id: product_form_id, class: 'form', novalidate: 'novalidate', x-ref: 'product_form' -%}
Let me know if it works :)
Source
Didn't find the answer?
Our community is visited by hundreds of Shopify development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.