Error encountered in Vue.js when attempting to implement a click event on a button

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.

Answer №1

In the comments, @Bennett Dams pointed out where the issue lies:

addProductToCart(product) {
    this.$store.commit("addProductToCart", this.product);
    this.$toastr("success", "Product added to cart successfully.");
},

The problem here is that your method accepts the product as a parameter, but then you are using this.product in your Vuex action (which is actually undefined). To fix this, you should modify your code as follows:

addProductToCart(product) {
    this.$store.commit("addProductToCart", product);
    this.$toastr("success", "Product added to cart successfully.");
},

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Obtaining a fresh access token from a refresh token using the googleapis npm library

I've been searching everywhere for an explanation, but I can't seem to find one. The documentation I've read says that refresh tokens are used to obtain new access tokens, but it doesn't explain the mechanics behind it. Normally, I wou ...

Having trouble retrieving the Node.js file via a POST request

After coming across similar questions without a solution, I am reaching out for help here. I have generated XML content programmatically and displayed it in a Textarea. Now, I need to provide an option for users to export or download this content to their ...

Tips for conducting performance analysis in React 16

In the React documentation, it is mentioned that react-addons-perf does not function with React 16 and suggests using Chrome's built-in tools for equivalent functionality. However, in my experience, I have not found this to be true. For example, let& ...

Having difficulty updating the complete reactive array in Vue.js

Below is the code snippet. Even though there are no errors, the output does not update as expected. Click here to view and run the code in Vue SFC Playground <script setup > import { ref, reactive } from 'vue' const arr = reactive([2,4,6] ...

Encountering difficulties with showing contact images in phonegap using angularjs

In my project, I encountered an issue where I can fetch and display the contact photo using simple HTML and JavaScript. However, when I attempt to do the same using AngularJS model, I encounter an error. Below is the code snippet that I am struggling with: ...

HTML combined with the Internet Explorer versions 6, 7, 8, and 9 can result in a div element that

My HTML code includes a <div>Some text</div>, and I am looking to ensure it is unclickable (allowing elements under the div to be selected instead), unselectable (preventing users from selecting text inside the div), while still being visible.. ...

Scrolling to the bottom of the screen on the next page results in a seamless One Page

Currently on my Magento website, I have encountered an unusual issue with the onepagecheckout functionality that needs to be resolved. When progressing to Step 2 and clicking on the continue button after entering all required data, the page automatically s ...

Static response is the way to go! Asynchronous responses just don't cut it

Currently in the process of developing an angular directive for displaying real-time charts. Below is the code snippet that encompasses everything, including link: function() { }, within the directive. Here's the code for a static directive that func ...

Customize the color of the active button in Bootstrap Vue

I'm currently utilizing bootstrap in conjunction with Vue.js. My form-checkbox-group setup looks like this <b-form-group label="Select flow" v-slot="{ ariaDescribedby }"> <b-form-checkbox-group v-m ...

Converting objects to arrays in reactJS

Here is the object structure I currently have: { DepositAmt_0: 133 DepositAmt_1: 455 DepositAmt_2: 123 DepositNotes_0: "some notes " DepositNotes_1: "some comment" DepositNotes_2: "some comme ...

An async/await global variable in Javascript is initially defined, then ultimately becomes undefined

As I work on establishing a mongoDB endpoint with NodeJS and implementing this backend, I encounter an issue within the code. In particular, the function static async injectDB sets a global variable let restaurants that is then accessed by another function ...

Struggling with NodeJs POST request issue

Let's imagine I have a specific URL https://exampleAPI.com/authorize?param1=value1&param2=value2 Where param1 and param2 are the payload values being sent. How can I execute a POST request in this particular way? I attempted the following: var ...

Warning: UnsupportedRepoVersionError: The repository versions are not compatible. Please check the version of IPFS-JS (0.55.3) and Node.js (14.17.0) being used

Recently, I delved into the world of ipfs js and currently have version 0.55.3 installed (https://www.npmjs.com/package/ipfs). Alongside, my setup includes node js version 14.17.0 (LTS) on MacOS BigSur 11.4. However, while following a tutorial at https:// ...

Is $timeout considered a questionable hack in Angular.js development practices?

Here's a question for you: I recently encountered a situation where I needed to edit the DOM on a Leaflet Map in order to manipulate the appearance of the legend. To workaround an issue where the map wasn't generating fast enough to access the n ...

Develop a diverse range of form types within Django forms

Even though I know how to create a form set based on a given form type, it doesn't completely resolve the issue at hand. Imagine having a fast food portal where users can add items and depending on their selection, additional fields need to be dynami ...

Is there a way to display multiple JSON object data by utilizing a Firebase snapshot? The data retrieval was successful

I have successfully managed to pull data from the snapshot to the console. Here is a snippet of the data: {34FrUM8777N6i0IWfqsatdMc29g1: {…}, 3DSOrtpBHlYENn14bE9UJKWly4G3: {…}} 3DSOrtpBHlYENn14bE9UJKWly4G3: -MH8EpUbn1Eu3LdT0Tj0: {code: "https://ww ...

Effective ways to narrow down data in vuetify v-autocomplete component using Fuse.js

In my application, I am using the Vuetify autocomplete component. This component allows for the use of a custom filter to filter input data. Below is an example of a custom filter for the autocomplete: customFilter (item, queryText, itemText) { const ...

A step-by-step guide on resolving the issue "Error: listen EADDRINUSE: address already in use :::5000" in the event of an error

node:events:495 throw er; // Unhandled 'error' event ^ Error: listen EADDRINUSE: address already in use :::5000 at Server.setupListenHandle [as _listen2] (node:net:1817:16) at listenInCluster (node:net:1865:12) at Server. ...

Leveraging next-generation JavaScript (NextJS), incorporate sass-loader for seamless inclusion of variables in each individual

I'm having trouble implementing a custom webpack configuration in my nextjs project. My objective is to automatically import @import "src/styles/variables.scss"; for all scss files in my application. I have successfully set up a webpack con ...

Looking to add some movement to your website? Learn how to make an image track your mouse pointer in a specific section of your webpage

I'm just starting out with web design and javascript, so please be patient. My goal is to have an image follow the mouse pointer only when it's within a specific section of my website. I've managed to make the image track the mouse cursor ...