Encountering issues with properly updating the Vuex store

Looking at my Vuex 2 store:

const datastore = new Vuex.Store({
  state: {          
    socketcluster: {
      connection: false,
      channels: []
    },
    selected_offers: []
  },
  mutations: {
    addOffer: function(offer) {
      datastore.state.selected_offers.push(offer) // facing an issue here - cannot directly access state.offers as it throws an undefined
    }
  },
  getters: {
    getOffers: function(){
      return datastore.state.selected_offers; 
    }
  }
});

In a Vue 2 component, I have the following code snippet:

  methods: {
    clicked: function(){
      console.log("Toggle Offer");
      if ( datastore.getters.getOffers.filter(function(o){ o.id == this.offer.id } ).length == 0 ) {
        // add it
        datastore.commit('addOffer', this.offer)
      } else {
        // TODO remove it
      }
    }
}

Upon triggering the method, the store changes are visible in this image: https://i.stack.imgur.com/knlHP.png

I'm encountering some issues with this approach. What could be the problem here?

Answer №1

When working with the vuex pattern, it's important to utilize actions instead of directly mutating the state from the component. This example demonstrates a simple way to implement Vuex in a Vue application. By using getters and mutations, you can manage the state of your application effectively.

const store = new Vuex.Store({
  state: {          
    socketcluster: {
      connection: false,
      channels: []
    },
    selected_offers: [ "offer1", "offer2"]
  },
  mutations: {
    addOffer: function( state, offer ) {
      state.selected_offers.push(offer);
    }
  },
  getters: {
    getOffers: function( state ){
      return state.selected_offers; 
    }
  }
});

new Vue({ 
    store,
    data: function() {
        return {
            offer: "offer3"
        }
    },
    methods: {
        clicked: function() {
            if ( this.offers.length === 2 ) {
                this.$store.commit('addOffer', this.offer)
            } else {
                // TODO remove it
            }
        }
    },
    computed: {
        offers: function() {
            return this.$store.getters.getOffers;
        }
    }
}).$mount( "#app" );
<script src="https://vuejs.org/js/vue.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vuex/2.3.1/vuex.js"></script>

<div id="app">
    <div v-for="offer in offers" > {{offer}}</div>
    <button @click="clicked"> clicked </button>
</div>

Answer №2

When working with mutations, it is important to remember that the first parameter passed is always the state object. This means that you are adding the entire state object to the selected_offers array.

Your mutation function should be structured like this:

mutations: {
  addOffer: function(state, offer) {
    state.selected_offers.push(offer)
  }
},

If you need further information on vuex mutations, you can refer to the official documentation.

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

Having trouble setting a value for a textbox in angularjs

Greetings! I am currently working on a web application using AngularJS. My task involves binding data from various API's to a textbox in my project. Below is the snippet of the HTML code where I attempt to achieve this: <input class="with-icon" ty ...

Executing AJAX calls within a forEach loop

I'm facing a challenge with a function that carries out a foreach loop on a list of views and needs to make an AJAX request for each view within the loop. Upon receiving the results in the success callback, it checks if a specific ID is returned and, ...

What is the best method to utilize a promise to delay the execution of a function until the data is received and stored

Currently, I am facing an issue with my API where the model variable is returning undefined before any data is populated in the return_array. I am unsure of how to implement promises or another method to ensure that the variable waits for data to be fille ...

Cheerio in node.js encounters a problem while reading HTML files

I am brand new to JavaScript and I've hit a roadblock with Node Cheerio. Any assistance would be greatly appreciated. The code I'm currently working on can be found here: https://github.com/zafartahirov/bitstarter. Once the issue is resolved, t ...

Having trouble with the pagination feature while filtering the list on the vue-paginate node

In my current project, I have integrated pagination using the vue-paginate node. Additionally, I have also implemented filtering functionality using vue-pagination, which is working seamlessly. Everything works as expected when I enter a search term that d ...

Utilizing AngularJs to connect server-generated HTML content to an iframe

My Angular app functions as an HTML editor that transmits the template to a server for rendering with dynamic data. The rendered content is then sent back to the client, where it needs to be placed inside an iframe for preview purposes. It appears that ng- ...

Ensure the date is displayed in the format of dd-mm-yyyy when using the input type=date

Here is the code I am currently using : <input type="date" class="form-control" id="training_date" name="training_date" placeholder=" select" value="" onfocus="(this.type='date')" onfocusout="(this.type='date')" max=<?php echo ...

A step-by-step guide on sending a fetch request to TinyURL

I have been attempting to send a post request using fetch to tinyURL in order to shorten a URL that is generated on my website. The following code shows how I am currently writing the script, however, it seems like it's not returning the shortened URL ...

Using window.location.replace() for redirection after AJAX call succeeds

Attempting to redirect the page after a successful ajax call, the code below is functional: $.ajax( { type: "POST", url: path, data: response1, contentType: "application/json", success: -> window.lo ...

Exploring the art of path zooming in d3.js

Trying to resolve this issue, I adjusted the geoJsonURL to handle a more intricate shape. Despite the new shape allowing the zoom method to function correctly, the shape itself appears completely distorted. Based on the Coordinate system: WGS 84 (EPSG:4326 ...

Struggling to use the innerHTML method to update a div within another div element?

<!DOCTYPE html> <html> <head> <title>Business Information Card</title> <script type="text/javascript"> window.onload = init; function init(){ var button = document.getElementById("populate ...

Ways to eliminate the blue selection box when dragging canvas objects in fabric framework

I've been trying to find a solution to remove the annoying blue highlight box that appears when dragging on the canvas while using fabric js, but so far I haven't had any luck. I've tried the following code, but it only works for text and n ...

Sending JSON data back to the server using KeyValuePair in C#

My goal is to send my JSON list back to the POST method (EditCompanyReportField) on the C# server side. The related parameter (fieldSorted) in my method is an array object, but the values are not being passed through. I have a few question marks regarding ...

What is the best way to extract data from the ajax.done() function?

My question revolves around the function shown below: $.ajax({ url: "../../getposts.php" }).done(function(posts) { var postsjson = $.parseJSON(posts); }); I am wondering how I can access the variable postsjson outside of the .done() function sco ...

What is the reason for npm and yarn to download multiple versions of jquery?

For the purpose of investigating how package managers like npm, yarn, and cnpm work in Node.js, I conducted an experiment. During the test, I came across two packages: jquery-dreamstream and jquery.tree. Both of them have a dependency solely on jquery wit ...

How to transfer data using props through the ":to" attribute of a router link in Vue.js

I am facing an issue with creating a router-link in Vue and passing a route name as a prop. What I am trying to achieve is the following: <template> <div> <router-link :to="myProps">Login</router-link> </div> </tem ...

What methods are available to verify all my (JavaScript) AJAX calls when they are being sent to Node.js?

My web app sends hundreds of HTTP requests to a Node.js API I created. I need to ensure that only authenticated requests are accepted by Node.js. The issue at hand: I don't want to manually update each AJAX request in my JavaScript code to include a ...

Ensure the left and right screen widgets remain fixed in their positions as the user scrolls down the page using the spacebar

Currently, I have a webpage that showcases products with a large height attribute. I am looking for a way to make the page scroll down when the user hits the space bar to view more products. However, I want my screen widgets such as the shopping cart and ...

In React (Next.js), the act of replacing a file is performed instead of adding a file

I kindly request a review of my code prior to making any changes. const test = () => { const [files, setFiles] = useState ([]); //I believe I need to modify the following statement. const handleFile = (e) => { const newFiles = [] for (let i= ...

Is Implementing a Promise for Preprocessing in NodeJS Worth It?

Looking to achieve the following using NodeJS + Express: Client sends a post request with JSON document data={text: "I love Stackoverflow", shouldPreprocess: <true or false>}; Need to call an external WebSocket service for sentiment analysis on the ...