Ways to incorporate additional values into an array object with Vuex

I'm new to using vuex and I am attempting to save objects into an array called orders within the store.js file.

My goal is to extract values from an object (such as me.title) and save them into an array within the store file by clicking on a button that triggers the triggerFunction method. However, I have encountered two issues:

1 - When checking the console log, I noticed that only the state.order.title variable is being updated while the others remain undefined (e.g., orders.calories).

2 - Additionally, the state.orders array is empty and no value is being pushed into it as expected by the mutation function.

app.vue

<template>
<p class="genric-btn primary circle text-uppercase" v-on:click="triggerFunction(me.title,me.description,me.price,me.calories)">add to cart</p>
</template>

<script>
export default {
    data () {
        return {
            me:{
                title:"Hamburger",
                description:"Something here",
                price:"25",
                calories:"10"
            },
        }
  },
methods:{
   triggerFunction: function(title,description,price,calories){  
      this.$store.dispatch('triggerFunction',title,description,price,calories)
    },
}
</script>

store.js

import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex);

export const store = new Vuex.Store({
    state:{
        order:{title:'',description:'',price:0,calories:0,qty:0},
        orders:[],
    },
    mutations:{
        triggerFunction: (state,title,description,price,calories) => {
            state.order.title = title,
            state.order.description = description,
            state.order.price = price,
            state.order.calories = calories
            state.order.qty = 1
            state.orders.push(state.order)
                        console.log(state.order)
                        console.log(state.orders)
        },
    },
    actions:{
        triggerFunction: (context,title,description,price,calories) => {
            context.commit('triggerFunction',title,description,price,calories)
        }
    },
})

Answer №1

  1. When working with mutations and actions, remember that they have 2 default parameters: the store's state and the payload.

  2. If the store is not observing object key changes, you can use Vue.set. It's acceptable if the store's order variable is not reactive.

  3. You can access data variables directly in the component without passing them as parameters, especially when not using v-for.

Here is the correct way to call the action:

<template>
    <p class="genric-btn primary circle text-uppercase" v-on:click="triggerFunction(me.title,me.description,me.price,me.calories)">add to cart</p>
</template>

<script>
export default {
    data () {
        return {
             me:{
                title:"Hamburger",
                description:"Something here",
                price:"25",
                calories:"10"
            },
        }
  },
  methods:{
      triggerFunction: function(title,description,price,calories){  
      this.$store.dispatch('triggerFunction', {
          title: title,
          description: description, 
          price: price, 
          calories: calories
      }) // or ES6 if the value name equals with the key {title,description, price, calories}
    },
}
</script>

Make sure your store is set up correctly:

import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex);

export const store = new Vuex.Store({
    state:{
        order:{title:'',description:'',price:0,calories:0,qty:0},
        orders:[],
    },
    mutations:{
        triggerFunction: (state, payload) => {
            Vue.set(state.order, 'title', payload.title);
            Vue.set(state.order, 'description', payload.description);
            Vue.set(state.order, 'price', payload.price);
            Vue.set(state.order, 'calories', payload.calories);
            Vue.set(state.order, 'qty', 1);
            state.orders.push(state.order);
        },
    },
    actions:{
        triggerFunction: (context, payload) => {
            context.commit('triggerFunction', payload)
        }
    },
})

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

Injecting multiple instances of an abstract service in Angular can be achieved using the following techniques

I am fairly new to Angular and currently trying to make sense of the code written by a more experienced developer. Please excuse me if I'm not adhering to the standard communication practices and vocabulary. There is an abstract class called abstract ...

Is it possible to organize elements in a given array based on their data type?

I am working on a script to determine the data type of each value in an array by using foreach() and var_dump(). Here is an example array that I am working with: $arr = ['this','is', 1, 'array', 'for', 1, 'exa ...

The Angular Table row mysteriously vanishes once it has been edited

Utilizing ng-repeat within a table to dynamically generate content brings about the option to interact with and manage the table contents such as edit and delete. A challenge arises when editing and saving a row causes it to disappear. Attempts were made ...

Utilizing Anglar 16's MatTable trackBy feature on FormGroup for identifying unaltered fields

In my application, I am working with a MatTable that has a datasource consisting of AbstractControls (FormGroups) to create an editable table. At the end of each row, there are action buttons for saving or deleting the elements. My goal is to implement tr ...

'addEventListener' and 'onclick' functions are restricted to the 'window' element and cannot be used on any other element, such as a button

I am currently working on developing a Snakes and Ladders board game using JavaScript. I have encountered an issue with adding 'onclick' or 'addEventListener' events to the buttons in the game. When I try to attach these events to the b ...

Checking the status of a Cisco Jabber user using JavaScript

How can I verify on my webpage if a user is available on the Cisco Jabber Client? I have both their number and username. I can currently send chat messages and start voice conversations, but I would like to display a cool icon or indicator if the user is o ...

Convert a Material UI dropdown into a Bootstrap dropdown

The reason for this transformation is due to the unsightly appearance of the dropdown from Material UI. Despite that, the code is functioning properly. It features a dropdown with multiple choices, loading a list of strings and their corresponding images. ...

Having trouble uploading the file to Firebase storage

While attempting to upload files to Firebase using React, I encounter a perplexing issue. The file upload progress bar hits 100%, only to present me with an unfamiliar error message: { "error": { "code": 400, "message": "Bad Request. Could not c ...

What are some tips for managing the hover effect using CSS3?

Here's a demonstration of my current setup. When you hover over the black box, a transition occurs and reveals my tooltip. However, I only want the tooltip to appear when hovering over the black box itself. Currently, the transition also triggers if y ...

Guide on configuring remix using aws cdk

Currently, I am delving into the world of remix and attempting to configure a remix project that utilizes AWS CDK for the server. I stumbled upon this GitHub example: https://github.com/ajhaining/remix-cloudfront-cdk-example However, it lacks clarity on ...

Interested in leveraging string functions on the information retrieved from the API?

I am trying to utilize String functions such as slice(x,y), length() on the data received from the API. To achieve this, I first converted the data to a variable called mystr using JSON.stringify(obj), but encountered an issue where the console displayed: ...

Connecting an Express JS application to the GitHub API: A Step-by-Step Guide

Just recently, I delved into using expressJS for the first time and found myself struggling to connect it to the github API. My aim is to execute commands that can help me retrieve comments and other information from a specific repository. I would greatly ...

What could be causing my bootstrap dropdown button to malfunction?

Even after selecting an option from the dropdown menu and pressing the button, the value does not change. I attempted to console log it using JavaScript but encountered an error in the Chrome inspector: index.js:26 Uncaught TypeError: Cannot read prop ...

Utilizing Ionic to seamlessly integrate Firebase into a factory, maintaining separation of controllers and services within distinct files

I'm struggling with setting up a firebase factory for use in my controllers. Currently, this is how my code appears: index.html ... <!-- integrating firebase --> <script src="lib/firebase/firebase.js"></script> <script src="lib/ ...

Difficulties encountered when attempting to populate a select dropdown with data fetched through an AJAX request

Currently, I am working on a small project that involves managing libraries. One of the tasks at hand is populating a select tag with all the libraries stored in my database. To accomplish this, I have developed a WebService which features a web method cal ...

Utilizing Zebra Printers for Seamless Integration and Printing in Ext Js

I'm currently working on developing an app in ExtJs that involves printing a PDF label for warehouse purposes using Zebra smartphones connected to printers via Bluetooth. I've been trying to implement Zebra's APIs specifically the BrowserPri ...

sending an array from one CodeIgniter view to another view via Ajax

In the following code segments of my application, myArray is an array where each element contains a few objects that I need to use in a second view. When I use alert(myJSON);, I am able to see the array in the alert window. However, when the view loads, i ...

What is the reason behind being able to pass a value to the printf function in C using this format?

While researching pointers in C, I came across a website where I found an interesting usage example: int main() { int i; int array[5] = {10, 20, 30, 40, 50}; for(i = 0; i < 5; i++) { printf("%d\n", i[array]); /* Using "i[array ...

Attempting to retrieve an object's attribute

Hey! I have a question regarding the screenshot in this link: I'm trying to access the user object with the property team. So far, I've attempted using data.Object, but it returns an undefined output. I also tried using data.user but that resul ...

Adjusting the size of a v-image in Vuetify to perfectly fit the screen dimension

I have a photo gallery on my Vue page, and when a photo is selected, a dialog pops up by setting the selectedCard. However, the image does not fit the size of the screen and only half of it is visible. I have tried setting the CSS with max height or widt ...