I am trying to add products to my shoppingcart but I keep bumping to the uncaught TypeError, since I am new to front-end development this is a pain in the ass for me.
This is the error that is shown to me.
If I go to the pointed javascriptfile I find this. The :4 throws on the product.quantity = 1; This is part of the Mutation.js
export const addProductToCart = (state, product) => {
product.quantity = 1;
state.cart.push(product);
};
When I go to the Action.js I see this code. This is going to check the index of the clicked object and add this to the cart.
export const addProductToCart = ({ state, commit }, product) => {
const exists = state.cart.find(exists => exists.Id === product.Id);
if (exists) {
commit("updateProductQuantity", product);
}else {
commit("addProductToCart", product);
}
};
Now to my ProductList.vue In the template content I added this code to my button for adding the product to the cart.
<b-button variant="primary" @click="addProductToCart(product)">
Add to cart</b-button>
For the same file here is the code of the whole script section.
<script>
export default {
name: "product-list",
props: {
products: {
type: Array,
required: true,
}
},
methods: {
view(product) {
this.$router.push (`/products/${product.slug}`);
},
addProductToCart(product) {
this.$store.commit("addProductToCart", this.product);
this.$toastr("success", "Product added to cart successfully.");
},
}
};
</script>
The index.js file
import Vue from "vue";
import Vuex from "vuex";
Vue.use(Vuex);
import * as actions from "./actions";
import * as mutations from "./mutations";
import * as getters from "./getters";
const store = new Vuex.Store({
strict: true,
actions,
mutations,
getters,
state: {
cart: [],
}
});
store.subscribe((mutation, state) => {
localStorage.setItem("store", JSON.stringify(state));
});
export default store;
Im stuck on this for a day or 2 already trying multiple different other options. But I do not find any solution.
Is there anything I am missing here? Is this code sufficient for finding a solution? Or do I need to search somewhere else.
Kind regards.
As mentioned by @Bennett Dams in the comments; The problem lives here:
addProductToCart(product) {
this.$store.commit("addProductToCart", this.product);
this.$toastr("success", "Product added to cart successfully.");
},
As you can see, your method takes the product
as a parameter, but then you are trying to send this.product
to your vuex action (and this.product
is indeed undefined
). You should replace your code by:
addProductToCart(product) {
this.$store.commit("addProductToCart", product);
this.$toastr("success", "Product added to cart successfully.");
},