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

Text centered vertically with jQuery is only loaded after the page is resized

My jQuery script is designed to vertically center text next to an image, but it seems to only work properly after resizing the page. $(window).load(function () { $(function () { var adjustHeight = function () { $('.vertical-al ...

How can I format the input type number with a thousand separator as 123.456.789?

When entering the number 123456, I want to see 123.456 displayed in the input field. I tried using my code, but it displays 123,456 instead. Is there a way to ensure that the thousand separator is a dot and not a comma? You can view my code at this link ...

Dividing image styles within css

I am trying to incorporate 4 arrow images into a CSS class (up, down, right, left). I started with a basic arrow css class: .arrow { background-repeat: no-repeat; background-position: center; } Next, I created subclasses like: .arrow .up { ...

Displaying Highcharts inside an infowindow by sending an AJAX request through Google Maps

After exploring the demo available here, I successfully created a map using data from my MySQL table. Now, my goal is to include a HighChart in the infowindow. However, despite several attempts, I am unable to make it appear. Ultimately, I aim to retrieve ...

I'm having trouble applying CSS stylings to my components in my React project. What could be the issue causing this?

As a React beginner, I am facing issues with getting my CSS to work properly in my project. I know that CSS is not used directly in React, but rather interpreted as JavaScript using webpack and babel. What have I tried? I attempted to make changes to my w ...

individualized django models field for each user

Is it possible to create a boolean field in the post model to track if a user has liked a post? This field should only be changed by the respective user and not affect others. For example, if user 1 likes a post, it should show as true only for that user ...

Error: Unable to resolve Vue dependencies

Currently, I am in the process of developing a Laravel application with Vite bundling. Within this Laravel setup, I am incorporating a package that contains Vue components. Below is my vite.config.js: import laravel from 'laravel-vite-plugin'; i ...

How can we leverage jQuery deferred within Backbone Marionette composite views, where each items view contains a form, to execute a task after each form submission is successful?

I am utilizing a Backbone Marionette composite view in which each child item view contains its own form. var DependentsFormFields = Backbone.Marionette.CompositeView.extend({ template: 'dependents_form_fields_wrapper', itemViewContainer: ...

Methods for presenting text from an object array using Angular

I'm running into a bit of trouble with getting my text to show up properly in my code. In the HTML, I have <td>{{cabinetDetails.cabinetType}}</td> and my data source is set as $scope.cabinetDetails = [{cabinetType: 'panel'}]; De ...

Styling a textbox within a gridview using JavaScript

Looking for a way to format a textbox within a gridview using JavaScript? Take a look at how the gridview columns are set up: <Columns> <asp:TemplateField> <ItemTemplate><asp:ImageButton runat="server" id="imgbtnEnterAmt" ...

Creating PDF documentation in a JavaScript architecture MVC framework, specifically utilizing Backbone.js

In my project, I have implemented a Backbone Marionette single page application that interacts with a RESTful API backend using RoR. I am interested in providing users with the ability to export a PDF report that includes specific rendered views, regions, ...

What are the steps to make a div with no content inside?

Presently, I am dealing with 2 overlapping transparent div's each containing unique buttons and functionalities in the following manner: .item1{ height:10rem; width:10rem; position:absolute; border:0.5rem solid red; background-color:trans ...

Library written in JavaScript for extracting CSS that is relevant

Is there a JavaScript tool available that can extract the style information from HTML code? For instance, when given the following HTML snippet, it would output a style block containing all the computed styles applied to each of those elements? Input... ...

Displaying the unique values based on the key attribute

I'm developing a category filter and struggling to showcase the duplicate options. Within my array of objects: filterData = [ { name: 'Aang', bender: 'yes', nation: 'Air', person: 'yes', show: 'ATLA&apo ...

Tips for aligning pagination in the MUI v5 table component and creating a fixed column

I am currently experimenting with MUI table components and have created an example below with pagination. const MuiTable = () => { const [page, setPage] = useState(0); const [rowsPerPage, setRowsPerPage] = useState(5); const [data, setData] ...

Having trouble retrieving the keyword property within a Vue.js promise

Struggling with an async validation process in Vue.js where I need to globally access the $axios instance, but encountering failures Validator.extend('async_validate_job_type', { getMessage: field => `The Name already exists`, val ...

Challenges encountered while formatting Json strings for WCF service transmission

I need assistance in connecting a JavaScript application to a WCF service. The WCF Service I have includes the following method: [OperationContract] [WebInvoke(Method = "POST", BodyStyle = WebMessageBodyStyle.Wrapped, RequestFormat = WebMessageFor ...

Create your own unique Semantic UI themes using the Semantic UI theme builder, complete with support for Font Awesome classnames and the ability to preview them with the

My admiration for Semantic UI and Semantic UI React knows no bounds. Not only are they phenomenal libraries, but their documentation is truly a work of art. Yet, crafting and keeping up with themes for these components can be quite the challenge. The task ...

Having difficulty showcasing API call results in a Vue.js component

I am currently experimenting with Vue.js in an attempt to showcase results from a Wikipedia API call within a component using the v-for directive. However, I seem to be encountering some backend issues that I cannot pinpoint. To access the jsFiddle link, ...

Having difficulty positioning two elements within a button using bootstrap

I am attempting to align two texts horizontally inside a button using Bootstrap 4. The word "Link" keeps getting pushed to the next line and I would like it to stay beside "Copy". I have experimented with using Float but it ends up moving "Link" too far t ...