State not responding to changes using Vuex framework

Is there a way to update the cart in Vuex by clicking on it without having to re-render the component or manually committing again in the Vue devtools?

This is how my store is structured:

  • state
state: {
  toggleSideBar: false,
  cart: [],
},
  • Action
action:{
  incrementCart: ({ commit }, payload) => {
  commit("INCREMENT_CART", payload);
},
 addToCart: ({ commit, state }, payload) => {
      commit("ADD_TO_CART", payload);
    },
}
  • mutation
mutation:{
  INCREMENT_CART(state, payload) {
    let index = state.cart.findIndex((x) => x.id === payload);
    state.cart[index].amount += 1;
  },
  ADD_TO_CART(state, payload) {
      let amount = 1;
      if (state.cart.length === 0) {
        payload.amount = amount;
        return state.cart.push(payload);
      } else {
        if (state.cart.some((cart) => cart.id === payload.id)) {
          let index = state.cart.findIndex((x) => x.id === payload.id);
          state.cart[index].amount += amount;
        } else {
          payload.amount = amount;
          state.cart.push(payload);
        }
      }
    },
}

  • then in my component
computed: {
  cartData() {
    return this.$store.state.cart;
    console.log(this.$store.state.cart);
  },
}

In this case, the value is passed as props to individual carts.

Answer №1

To access the cart data in Vuex, you should define a getter as shown below:

getters: {
    getCartData(state) {
        return state.cart;
    }
}

In your component's computed properties, use mapGetters to call the getter like this:

import { mapGetters } from 'vuex';

export default {
    
    computed: {
        ...mapGetters(['getCartData']);
    }
}

Lastly, retrieve the cart items from the getter in your HTML template:

<div v-for="item in getCartData">{{ item.quantity }}</div>

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

Encountering an issue: ReferenceError: regeneratorRuntime is not defined when implementing react-speech-recognition in nextjs13

Encountering the errorReferenceError: regeneratorRuntime is not defined in my NextJS project I'm currently using Redux toolkit. Link to my project. Please note that the code triggering the error can be found under the nextjsfrontend branch. I' ...

the process of altering properties in vue js

After running my Vue file, I encountered the following console error. As someone new to Vue programming, I'm attempting to utilize a Syncfusion UI component to display a grid. Prop being mutated: "hierarchyPrintMode" I am unsure where to add the comp ...

What sets apart $.replaceWith() from the combination of $.remove and $.appendTo()?

I have noticed that when using these two pieces of code, I get different outcomes. In theory, they should yield the same result. What exactly sets them apart? var mapString = '<map id="map"><area shape="poly" coords="52,21,92,21,92,196,52,19 ...

The sorting feature for columns seems to be malfunctioning in Bootstrap 5

I have utilized bootstrap 5 to create a table, but I am facing an issue when trying to sort the first column as there is no change reflected. Below is how my table is structured: The structure of the table is as follows: <table class="table" ...

Encountered a server issue (500 Internal Server Error) when attempting to send a POST

I have been working on a social media app project using React and MongoDB. However, every time I try to register a user, I encounter a POST error in the console. I have reviewed both my client-side and server-side code, but I am still unable to successfull ...

Access exclusive content by subscribing now!

How can I return a reference to a subject from a service without allowing the receiver to call .next() on the subject? Let's say there is a service with a subject that triggers new events. class ExampleService { private exampleSubject = new Subjec ...

Creating unique sizes for each quad in Three.js using InstancedBufferGeometry and ShaderMaterial

I'm working on creating a visually dynamic scene filled with points of varying widths and heights. The challenge I'm facing is figuring out how to manipulate the vertices in the vertex shader to achieve customized sizes for each point. Here' ...

JavaScript array increasing its length too soon

I am experiencing issues with the length of an array in a condition-based scenario. The problem I am facing is that the array does not increase at the expected time. To better illustrate my issue, I have created a Plunker with sample code: Upon clicking " ...

Contrasting document and $document in AngularJS

What sets apart the usage of document from $document in Angular application development? I have come across recommendations to opt for Angular's counterparts like: $window over window or $timeout instead of setTimeout. But... why is this advised? I i ...

Ways to Randomly Flip Divs

I have developed an application where all divs flip vertically on hover. I am looking for a way to make the flipping random without requiring a hover. Any ideas on how to achieve this? .vertical.flip-container { position: relative; float: left; ma ...

How can we stop KeyboardAvoidingView in React Native from overlapping content?

I'm working on implementing a KeyboardAvoidingView section for a signup form. I've managed to adjust the keyboard properly on both iOS and Android, but instead of increasing the view's height and scrolling up, the KeyboardAvoidingView is red ...

Creating a Node.JS application, developing an Express JS API, and handling errors

I am facing challenges while developing a REST API in Express.js and I am seeking assistance. Below is my Express.js code: router.get( '/apps/download/:downloadId', function ( req, res, next ) { const opts = Object.assign( {downloadId: re ...

Notification triggering twice in React application

My issue is that the alert for an invalid login keeps running twice in my react project and I cannot seem to pinpoint the reason. After authenticating with the server side, I receive a true or false response which I then set to userLogin. const [userLogin, ...

Encountering difficulties in the installation of a package within Next JS

Can anyone assist me with this issue I'm facing while trying to install styled-components on Next JS? I keep getting an error after entering npm install --save styled-components: npm ERR! Unexpected end of JSON input while parsing near '...ry.np ...

Whenever I attempt to populate my modal box with data from my selection, I am greeted with an error message stating "invalid object passed in." What could be causing this issue?

Whenever I click on a customer from my table to display their details in a modal box, I keep getting an error message that says "invalid object passed in." The method client is responsible for populating the data and displaying it through a partial view. T ...

Creating a simple chatbot using jQuery and Ajax, and implementing a feature to ignore lowercase inputs

I'm currently working on a chatbot project and I'm having some difficulties with the input identifier. if (message.indexOf("how are you")>=0){ send_message("Thanks, Iam good!"); responsiveVoice.speak("Thanks, Iam good! ...

Access a SQL database to retrieve a data value and seamlessly integrate it into an HTML document with the help of node

I am new to web development and currently facing a challenge in displaying SQL content on an HTML page. My stack includes Node.js, Express, and SQLite3. I have a folder named public containing HTML, CSS, and JS files. The objective is to retrieve a varia ...

Is your jQuery .on function failing to properly detect click events?

Seems like I'm missing something here. Why is the .on function not functioning as expected in this code snippet? <html> <head> </head> <body> <button type="button" class="close" data-test="test">TEST BUTTON< ...

Is it possible to store dat.gui presets for controls that are dynamically added?

I have a dynamic dat.gui interface where I add controls, but the "save settings" feature doesn't seem to recognize them. var mygui = new dat.GUI(); mygui.remember(mygui); // Example of adding a control in the standard way mygui.control1 = 0.0; var c ...

Tips for creating a virtual scrolling feature

I am looking to create a virtual scroll feature using HTML, JS, and Vue. While trying out vue-virtual-scroll, I encountered difficulties in customizing it to fit my needs. As a result, I have decided to build a basic version from scratch and then apply t ...