How can VueJS manipulate state with Mutation?

I have set up a Vuex Store that returns data on headers and desserts. The desserts object includes a property called display, which is initially set to false. In my project, I am using a component called Row within another component named Table. The Row component accepts props such as Name and Display, where the Display prop comes from the Vuex store's desserts data. I'm attempting to create a mutation that toggles the value of display.laptop between true and false when an icon in the Row component is clicked. However, I keep encountering an error message saying 'cannot read property laptop of undefined'.

Please check out the full code on CodeSandbox.

Here is the complete code:

The Vuex Store:-

export default new Vuex.Store({
  state: {
    headers: [{ text: "Dessert (100g serving)", value: "name" }],
    desserts: [
      { name: "Lollipop", display: { laptop: true } },
      { name: "Marshamallow", display: { laptop: false } }
    ]
  },
  getters: {
    getHeaders: state => state.headers,
    getDesserts: state => state.desserts
  },
  mutations: {
    toggleLaptopDisplay(state) {
      state.desserts.display.laptop = !state.desserts.display.laptop;
    }
  }
});

This is the Table Component:-

<template>
  <v-data-table :headers="getHeaders" :items="getDesserts" hide-actions select-all item-key="name">
    <template v-slot:headers="props">
      <tr>
        <th v-for="header in props.headers" :key="header.text">{{ header.text }}</th>
      </tr>
    </template>
    <template v-slot:items="props">
      <tr>
        <Row :name="props.item.name" :display="props.item.display"/>
      </tr>
    </template>
  </v-data-table>
</template>

<script>
import { mapGetters } from "vuex";
import Row from "./Row";
export default {
  components: {
    Row
  },
  data() {
    return {};
  },
  computed: {
    ...mapGetters({
      getHeaders: "getHeaders",
      getDesserts: "getDesserts"
    })
  }
};
</script>

This is the Row component:-

<template>
  <div>
    {{name}}
    <v-icon @click="toggleLaptopDisplay" :color="display.laptop ? 'info': '' ">smartphone</v-icon>
  </div>
</template>

<script>
import { mapMutations } from "vuex";
export default {
  props: {
    name: String,
    display: Object
  },
  methods: {
    ...mapMutations({
      toggleLaptopDisplay: "toggleLaptopDisplay"
    })
  }
};
</script>

Any assistance would be greatly appreciated. Thank you :)

Answer №1

Here are a few steps to help you achieve your desired outcome:

First, within your Row.vue file, include a method to select the appropriate element:

<v-icon @click="toggleChange" :color="display.laptop ? 'info': '' ">smartphone</v-icon>

Next, in the methods section, create a function that will pass the name of the element as a payload:

methods: {
    toggleChange() {
        this.toggleLaptopDisplay(this.name)
      },
    ...mapMutations({
      toggleLaptopDisplay: "toggleLaptopDisplay"
    })
  }

Finally, in your store.js file, use the payload to update the selected element:

mutations: {
    toggleLaptopDisplay(state, payload) {
      state.desserts.find(dessert => dessert.name === payload).display.laptop = !state.desserts.find(dessert => dessert.name === payload).display.laptop
    }
  }

View Edited Example for reference

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

Ajax continues to operate even if an error is detected

Hello fellow programmers! I'm currently facing an issue with form submission and validation using jQuery with 2 ajax events. The problem lies in the fact that even if the first ajax event (timeconflict.php) returns an error, the second ajax event (res ...

Searching for the index of a nested array in jQuery using JSON

I am currently working on developing an image uploader using Codeigniter3 along with jQuery and Ajax. Problem: I am facing difficulty in understanding how to locate the index of the array received from the ajax response shown below. Here is the data retu ...

The type 'undefined' cannot be assigned to the type 'string | Buffer | { key: string | Buffer; passphrase: string; } | GetPublicKeyOrSecret'

Verification Code for JWT This function is used to verify a jwt using typescript. public verify( token: string, secretOrPublicKey?: string | Buffer, options?: jwt.VerifyOptions ): Promise<object | string> { if (!secretOrPublicKey) { ...

Native JavaScript does not handle AJAX responses correctly

I'm facing an issue with my ajax call where the returned HTML works well on changes, but the Javascript that should perform actions based on clicks within the results is not functioning properly. Here is the ajax call: function update_order_shipp ...

Using Leaflet to beautify categorical json information

As a beginner in coding, I must apologize if a similar question has already been asked. I've spent days searching but haven't found the right combination of terms to find examples for my scenario. I am exploring various small use cases of differ ...

Using Typeof in an IF statement is successful, but attempting to use ELSE with the same

My goal is to create a JavaScript variable called str. In case the ID idofnet doesn't exist, I would like to prompt the user for a value to assign to str. However, if idofnet does exist, then I want to retrieve its value and assign it to str. This is ...

Sending an axios GET request to an Express server works flawlessly on the initial attempt

I'm facing an issue while setting up a route to download videos in my Vue app, which is backed by an Express server. The first request sent to the backend works fine and the file is downloaded successfully. However, subsequent requests fail with a Net ...

Using Javascript/JQuery to extract numbers from a URL with regex or alternative methods

I need help extracting a specific group of consecutive numbers from the following URLs: www.letters.com/letters/numbers/letters" and www.letters.com/letters/letters/numbers/symbols Is there a way to isolate only the continuous sequence of numbers in th ...

When trying to access the same path, useEffect does not trigger

I integrated the API to execute when the screen is loaded using useEffect in Next.js v10. The code implementation is straightforward: ... const fetchAPI = async () => { try { await axios.get({ .... }) } catch (e) { console.error(e) } } R ...

Stepping inside the realm of object-oriented programming, one might wonder how to initialize an object

I wrote this user.js function but I am having trouble creating an instance of it in another file. It seems like the structure is a function that contains a class which has functions within it. user.js 'use strict'; const {Sequelize} = require(&a ...

Encountering a problem with AngularJS - receiving the [ng:areq] error, for more information visit http://errors.angularjs.org/1.3.2/ng/areq

While working on my CRUD angularApp, I encountered a strange error in Chrome dev tools. Here is the complete error message: error: [ng:areq] http://errors.angularjs.org/1.3.2/ng/areq?p0=DbController&p1=not%20a%20function%2C%20got%20string at angular.j ...

What is the process for incorporating ejs into the source attribute of an image element?

Code Snippet: <img class="card-img-top" alt="..."><%= articles.image %><img> Server Setup: const express = require('express') const app = express() const router = require('./routes/article') app ...

Guide on activating an event when a slider image is updated using jquery

I am working on a project that includes a slider. I have been trying to trigger an event when the slider image changes, but so far using the classChange Event has not been successful. Here is the link to my code: [1] https://codepen.io/anon/pen/gzLYaO ...

Issue with VueJS rendering data within a for loop

As a newcomer to VueJS, I appreciate your patience as I navigate through this. Let me provide as much detail as possible. I am currently working on a Vue app that needs to retrieve a response from a server, iterate through the data, and set a Vue data var ...

Can you explain the process of utilizing WebdriverIO (wdio) to determine the frequency of an element's occurrence?

Currently, I am working on creating an interaction test to validate my javascript code using WebdriverIO (wdio). The specific functionality I am looking to test involves deleting a node and verifying that the number of times a selector appears has decreas ...

"Implementing a dynamic way to assign values to different item types in React

There is an object with multiple values inside: const [sort, setSort] = useState({ "city": [], "price": [], "year": [] }); When the "add" button is clicked, the "city" value should be updated to include certain va ...

Selenium - How to pass a file path to a dynamically generated input element that is not visible in the DOM

Check out this example of HTML code: This is how you create a visible button and display the selected file: <button id="visible-btn">visible button</button> <p>selected file is: <span id="selected-file"></spa ...

What is the best method to securely install a private Git repository using Yarn, utilizing access tokens without the need to hardcode them

My initial thought was to utilize .npmrc for v1 or .yarnrc.yml for v2/3/4, but in all scenarios, Yarn does not even attempt to authenticate with Github. nodeLinker: node-modules npmScopes: packagescope: npmAlwaysAuth: true npmAuthToken: my_perso ...

Using Vuex to iterate through an array of objects and implement a conditional statement based on a specific key-value

In my VueX implementation, I am fetching data and then iterating through an array of objects to extract the menu_code. The objective is to display or hide a button based on the following conditions: Show the button if at least one item in the menu_code ar ...

Updating text color with Ajax response value

I need assistance with updating the text color of a sensor value displayed using html/ajax. Currently, the sensor value is being displayed successfully, but I want the text color to change based on the value. Here's an example: if value < 50 then f ...