Struggling to add products to my shopping cart due to an uncaught TypeError, as a newbie in front-end development, this is quite frustrating.
The error message I am encountering can be viewed here: https://i.sstatic.net/L9UKy.png
Upon inspecting the JavaScript file mentioned, the issue seems to arise at line 4 with the code snippet Mutation.js:
export const addProductToCart = (state, product) => {
product.quantity = 1;
state.cart.push(product);
};
Another piece of code contributing to the problem can be found in Action.js, it involves checking for existing items in the cart before adding new ones:
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);
}
};
In ProductList.vue, the button script responsible for adding products to the cart is shown below:
<b-button variant="primary" @click="addProductToCart(product)">
Add to cart</b-button>
The complete script section within ProductList.vue file:
<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>
Lastly, the content of 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;
Been stuck on this issue for a couple of days now and exploring various alternatives without success. Any insights or suggestions would be greatly appreciated.
Any vital pieces missing in the code above? Suggestions for resolving this dilemma?
Thanks in advance.