Observing an array being stored in Vuex within a VueJS application

I currently have a list of customers stored as an array of objects in Vuex. When rendering this list in my component, each row includes a checkbox using Keen-UI:

<tr v-for="customer in customers" :class="{ selected: customer.selected }">
    <td>
      <ui-checkbox :value.sync="customer.selected"></ui-checkbox>
    </td>
    <td>{{ customer.name }}</td>
    <td>{{ customer.email }}</td>
</tr>

However, the checkbox directly modifies the customers array, which is causing issues because I am using strict mode in Vuex and it throws an error.

I need to track changes made to the array and then call an action to update the Vuex state accordingly:

watch: {
 'customers': {
  handler() {
    // ...
  },

  deep: true
}

Even with this setup, the customer object is still being changed directly. How can I go about resolving this issue?

Answer №1

Before anything else, exercise caution when utilizing the .sync feature as it is set to be phased out in version 2.0.

Refer to this resource: http://vuex.vuejs.org/en/forms.html, as it addresses the issue at hand. Essentially, this checkbox should initiate a vuex action upon input or change events. As outlined in the documentation:

<input :value="message" @input="updateMessage">

The function updateMessage appears as follows:

vuex: {
  getters: {
    message: state => state.obj.message
  },
  actions: {
    updateMessage: ({ dispatch }, e) => {
      dispatch('UPDATE_MESSAGE', e.target.value)
    }
  }
}

If you prefer not to monitor the mutations, you have the option to shift the state of this component away from vuex, enabling the full utilization of v-model.

Answer №2

To implement a custom getter and setter, follow these steps:

<template>
    <ui-checkbox :value.sync="thisCustomer"></ui-checkbox>
</template>

<script>
    //Using Vuex 2.0 syntax
    export default {
        thisCustomer: {
            get() {
                return this.$store.state.customer;
            },
            set(val) {
                this.$store.commit('SET_CUSTOMER', val);
                // Alternatively, you can use an action:
                  // this.$store.disptach('updateCustomer')
            }
       },
   }
</script>

In your store file:

import {
    SET_CUSTOMER,
} from '../mutation-types';

const state = {
    customer: null,
};

const mutations = {
    [SET_CUSTOMER](state, value) {
        state.customer = value;
    },
}

This example may need adjustments based on your specific store setup, but it should help guide you in the right direction :)

Answer №3

When your clients are in the main state, you might want to attempt the following approach:

watch: {
 '$store.state.clients'{
   handler() {
    // ...
   },

   deep: true
 }
}

Answer №4

experiment with mapState within your component and observe how it affects the customers, similar to what you demonstrated earlier. It made a difference for me.

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

Error in parsing JSON: An unexpected token < was encountered at the beginning of the JSON input, causing a SyntaxError at position 0 when parsing with

I need to transfer an array from a PHP file to JavaScript and save it in a JavaScript array. Below is the snippet of JavaScript code: xmlhttp = new XMLHttpRequest(); xmlhttp.onreadystatechange=function(){ if (xmlhttp.readyState==4 ...

Tips for creating a responsive image using Material-UI

I’m facing some challenges in making my page responsive. Specifically, I'm having trouble ensuring that an image remains within the grid container in material UI. Is there a method for making images responsive in this context? Even when I try adding ...

Substitute link with asynchronous JavaScript and XML

I need to enable/disable user accounts by clicking on an anchor. The list of users is created dynamically using a loop. Here's an example of an anchor tag: <a href="http://www.example.com/users/deactivate/44" class="btn btn-success" title="Deactiv ...

Bootstrapvalidator does not function properly with select2.js

My code is not validating the select field. What could be causing this issue? Can anyone provide a solution? Apologies for my poor English, and thank you in advance for your response. Here is my form: <form name="form_tambah" class="form_tambah"> ...

PhpStorm alerts users to potential issues with Object methods within Vue components when TypeScript is being utilized

When building Vue components with TypeScript (using the lang="ts" attribute in the script tag), there is a warning in PhpStorm (version 2021.2.2) that flags any methods from the native JavaScript Object as "Unresolved function or method". For exa ...

Developing an interactive graph with Django and harnessing the power of chart.js

I’m currently navigating the world of Django as a newcomer. My current project involves conducting sentiment analysis on real-time user tweets using the Twitter API. I've successfully analyzed and displayed the sentiments extracted from these tweets ...

Tips for avoiding unnecessary re-renders

The component I created sends props to both the checkbox and range components. During testing, I noticed that when a change was made in the range component, the checkbox also re-rendered even though it wasn't changed, and vice versa. Issue: When ...

What causes the other array to be affected when one is changed?

Take a look at this snippet of JavaScript code: var x = [1, 2, 3], y = x; y[1] = 3; x; // x === [1, 3, 3] Why does this happen? Why is the value of "x" changing when I update "y[1]"? I tried it in both Firefox and Chrome and got the same result. Th ...

Unable to use href attribute as intended

HTML: <a id="Switch">Click here to switch</a> <a href="image1_large.png" class="mainA blade"> <img id="mainImage" src="image1.png"/></a> Javascript: <script> $(function() { $('#Switch').click(functio ...

What is the best way to implement promise function in a JavaScript functional method such as forEach or reduce?

I have implemented a promise function in the following way: // WORK let res = {approveList: [], rejectList: [], errorId: rv.errorId, errorDesc: rv.errorDesc}; for (let i = 0; i < rv.copyDetailList.length; i ++) { const item = rv.copyDetailList[i]; ...

How can Symfony 2 and PHP be used to compare differences between objects within arrays?

In my project using Symfony 2.7, I have created a form that returns an array of objects when submitted. I am looking to compare this array with the existing data in the table. Here is how the form is set up: $builder ....... ->add('my_o ...

Exploring the concept of JavaScript nested promise scopes within the context of AngularJS

I've been struggling with JavaScript promises for the past few hours, trying to fix a problem that I just can't seem to solve. My knowledge of promises is limited, so I'm open to the possibility that my approach might be incorrect. Currentl ...

Bug with FullPage scrollOverflow sections when scrolling with iScroll's scrollTo() function

I've encountered an issue while using FullPage with scrollOverflow: true. I need to scroll to a specific position in a scrollable section. The problem arises from the fact that FullPage utilizes a modified version of the iScroll plugin for these overf ...

Retrieving Results from Sequenced Promises

I am facing an issue with returning data from a chained promise. In the following scenario, how can this be achieved? Here is some pseudocode: mark = function(){ return promiseA .then(function(data){ .....}) .then(function(data){return ne ...

Creating a game of Black Jack using a prebuilt deck class

In our recent class assignment, we were tasked with implementing the ArrayBag class, which is widely available online. The next step is to utilize this class to create a Black Jack game. However, I am facing some challenges in figuring out how to proceed w ...

Sending a POST request using Axios to the 'appName/v1/users/' route (using Djoser) results in a 401 error, whereas Postman does not encounter this issue

As I delve into Django, I am embarking on the task of setting up basic user authentication with a REST API and a Vue.js frontend. The method I am using to send requests is through axios, which is first configured in a separate composable file named axios.j ...

Save a text as a CSV file while also preserving any commas within the

I am trying to export a string to csv format while ensuring that commas inside the string are not treated as separators. For example: [{"name":"ALIASED_LINE_WIDTH_RANGE","value":{"0":1,"1":1}}] Even when ...

Having difficulty creating JSON data following retrieval of rows by alias in MySQL

I am encountering an issue while trying to fetch rows from two tables using a JOIN and aliases. The problem arises when I attempt to convert the fetched rows into JSON data and assign them to a JSON array. Below is the code snippet: $personal = $db->p ...

Encountering unexpected props in Components upon clicking links within React-router

I am currently developing a User page that displays individual profiles for each user. The profile page is functioning properly upon initial loading. However, I am facing an issue where if I am viewing the profile of user1 and then navigate to the profile ...

Having trouble with my initialData in react-query - any suggestions on how to fix it?

I encountered an issue while trying to implement code using initialData in React Query. The output does not display as expected, and the key is not visible in the react-query-dev-tool. View image here import { useQuery, useQueryClient } from 'react-qu ...