Refresh the DOM based on changes in Vuex store state

One of the issues I'm facing is with an 'Add To Basket' button that triggers a Vuex store action:

<button
  @click="addToBasket(item)"
>
  Add To Basket
</button>

The Vuex store functionality looks like this:

const actions = {
    addToBasket({ commit }, item) {
        commit("setBasketItems", item);
    }
};

const mutations = {
    setBasketItems: (state, item) => {
        let basketFind = state.basket.find(i => {
            return i.id === item.id;
        });

        if (basketFind) {
            basketFind.quantity += 1;
            return;
        }

        item.quantity = 1;

        state.basket.push(item);
    }
};

const state = {
    basket: []
};

const getters = {
    basketItems: state => state.basket,
};

Although the Vuex store contains the correct information, when trying to update the DOM to display the item's quantity it faces some challenges:

computed: {
  computedBasketItems: function() {
    return this.$store.getters.basketItems;
  }
},
<CartItem
  v-for="item in computedBasketItems"
  :key="item.id"
  :item="item"
/>

However, the issue arises when displaying the quantity for each item. It only shows '1' and does not update when the quantity changes.

To tackle this problem, one approach could be to...

Answer №1

  const updateBasket = {
    updateItems: (state, item) => {
      // check if the item id matches any existing basket item id and return the first matching element
      let itemInBasket = state.basket.find((i) => {
        return i.id === item.id;
      });

      // determine if the itemInBasket contains a value (if the array contains this item)
      if (itemInBasket) {

        // if itemInBasket is true, execute this block of code
        state.basket = state.basket.map((x) =>
          x.id === item.id ? { ...x, quantity: x.quantity + 1 } : x
        );

        // reassign the basket property in the state with the modified data
        // increase the quantity property of the matched element if x.id === item.id
        // leave other elements in the state.basket array unchanged
        return;

      }
      // if itemInBasket is false, proceed to this line of code
      // reassign the basket property in the state by adding existing elements and a new element with a quantity property set to 1
      state.basket = [
        ...state.basket,
        ...[item].map((x) => ({ ...x, quantity: 1 })),
      ];
    },
  };

Answer №2

The issue lies in the reactivity of your added items. While the basket array is reactive and will trigger a rerender when you add an item, the individual items themselves are not reactive. Simply pushing the item into the array without using Vue's $set method means that any changes to the item's properties won't trigger a reactive update. To solve this, swap out basketFind.quantity += 1; with

Vue.$set(basketFind,'quantity',basketFind.quantity+1)
for proper reactivity.

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

Upgrade angular-chart.js when applied to a filtered collection

I recently started working with Angular and encountered an issue while incorporating Angular Charts JS. I have a list that can be filtered using search text, and I want my charts to update whenever the list is filtered. What would be the best approach to ...

What's the best way to add line numbers to source code on an HTML webpage after parsing?

I am currently working with AngularJS and MongoDB. In my MongoDB data, there are some text elements that contain a \n, causing each line to be displayed on a new line based on the occurrence of \n. However, I also want to add line numbers to each ...

URL not functioning properly on Django CMS menu

After setting up django-cms and creating a collapsible menu with categories and subcategories, I encountered an issue. When clicking on a main category, the URL appears correct but it does not navigate to the corresponding page. Main categories without chi ...

Unable to fetch JSON data from PHP with the help of AJAX

I seem to be encountering an issue with retrieving JSON string data from my PHP script using an AJAX call. Here are the relevant scripts: $.ajax({ type: "POST", async: false, dataType: "json", url: "databas ...

Learn the process of transferring information through ajax while managing dependent drop-down menus

I have successfully set the initial value from the first combo-box and now I am looking to send the second variable from the second combo-box and receive it in the same PHP file. Below is the Ajax code snippet: $(document).ready(function(){ $(".rutas") ...

Exploring the Touch Feature in Angular

I am facing an issue with touch events as I am not receiving any useful X/Y coordinates. The event object does not provide the necessary information I need for touch events (https://developer.mozilla.org/en-US/docs/Web/API/TouchEvent/changedTouches). Despi ...

javascript unusual comparison between strings

I am working on an ajax function that is responsible for sending emails and receiving responses from the server in a JSON format with type being either success or error. $("#submit_btn").click(function(event) { event.preventDefault(); var post_d ...

The presence of decimal values within an AJAX URL

Struggling to pass decimal values in an AJAX request to a server-side endpoint. Everything runs smoothly except when trying to include a decimal value in the URL. The "." character is recognized as reserved within the URL schema, causing a 404 error. Seeki ...

Conditional styling in React class components depending on the props provided

Dealing with older versions of material-ui that cannot be updated. I'm attempting to modify the background of the Paper component based on various prop combinations without relying on the makeStyles HOC. Is this achievable? The issue seems to lie in ...

Ways to retrieve data from response instead of subscription JSON in Angular 2/4

My Service : retrieveData(url,request) { return this.http.post(this.apiUrl+url,request).subscribe( (response) => {return response.json()} ); } My Component : ngOnInit() { this.data = this.dataService.retrieveData(&apos ...

Check if the statement description on credit card statements is valid using regular expressions

I need to validate a user-entered string that will be used as the description on a credit card statement to describe a purchase. Here are the requirements: The string must be between 5 and 22 characters long It should have at least one letter (uppercase ...

Using node.js to download files with axios, streaming the content, and then

I am attempting to download a PDF file using axios, and save it on the server side using fs.writeFile. My code is as follows: axios.get('https://xxx/my.pdf', {responseType: 'blob'}).then(response => { fs.writeFile('/temp/my ...

Altering the display attribute cancels out any opacity transitions

When using JavaScript to change the opacity of an element with transition: opacity 1s, the expected duration of one second is met, as demonstrated here: onload = e => { var p = document.getElementsByTagName("p")[0]; p.style.opacity = 1; }; p { ...

Troubleshooting a LESS compiling issue with my Jade layout in ExpressJS

Implementing LESS compilation on the server side using Express was successful, but I faced an issue with jade not recognizing less in layout. Error message displayed in my terminal: if(err) throw err; ^ Error: ENOENT, open '/Users/li ...

Guide: Displaying components within a Vue2 string

Within my Vue2 component, I am working with a string that looks something like this: <template> <div><h1>Hello World</h1> <div v-html="testString"></div> </div> </template> <script> exp ...

Invalidating the express response object due to a TypeError issue

Currently, I am in the process of writing a test that utilizes sinon and sinon-express-mock to mock an incorrect request. The goal is to then call a validation function within my application and verify that it returns the expected response status code (400 ...

Starting the download of the canvas featuring a stylish border design

I'm facing an issue where the canvas border is not showing up when I download the canvas with a border. The border appears on the screen, but it doesn't get included in the downloaded canvas. let canvas=qrRef.current.querySelector("canvas&qu ...

The Map/Reduce function is producing incorrect results because of null values, causing me to receive NaN or erroneous

I am ready to delve into another Map/Reduce query. Within my database, I have a collection named "example" which is structured like this: { "userid" : "somehash", "channel" : "Channel 1" } The Map/Reduce functions I am using are as follows: var map = f ...

Does React reassign keys once the underlying data structure has been modified?

Exploring the ins and outs of React, particularly diving into how the Reconciliation process functions. In my JSX code, I have a map function that looks like this: render: function () { var currentIssues = this.state.issues.map(function(issue, ...

Efficiently input text box values into a canvas in real-time using HTML canvas and keypress

There are three text boxes labeled textbox1, textbox2, and textbox3. I am looking to transfer the values entered into these text boxes directly onto a canvas (cnv) whenever a user types in them, and remove the value from the canvas when it is deleted fro ...