Is there a way to modify the value of an object in a Vuex store using actions in Vue.js?

I have data stored in an array within the state and I need to update a specific object. How can I change the value of the object with id 1 to true using Vuex actions?

state.js

const array=[]

mutations.js

storeArray(state, data) {
    state.array = data;
  }

actions.js

async modifyValue({ state, dispatch, commit }, id) {
    const item = await state.array[id].value;

    await commit('storeArray', { value: true });

  },

The array's current structure is

[{
    id: "1",
    value: 'false'
}, {
    id: "2",
    value: 'true'
}]

Answer №1

Prior to making any changes, it is essential to have knowledge of both the id and value of the new array. To locate and modify the desired object within the state array, you can utilize the mutation outlined in the following example:

const store = new Vuex.Store({
  state: {
    objects: [{ id: 1, value: true }, { id: 2, value: true }]    
  },
  mutations: {
    changeObjectValue (state, { id, value }) {
        const found = state.objects.find(item => item.id === id);
        found.value = value;               
    },
  },
});

By following this approach, you can execute a commit within a single action like so:

store.commit('changeObjectValue', {id: 2, value: false});

To see this example in action, check out plnkr.

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

Refresh the copyright year by syncing with a time server

Not long ago, I found myself needing to update the copyright year on a website. Instead of using JavaScript to get the year from the system time, I began wondering if there was a way to utilize an internet time server for this purpose. I believe that util ...

Combining JavaScript JSON objects with corresponding parameters

I'm struggling to find a solution for merging two JSON objects. Despite searching for answers, I haven't found any that have been helpful. My goal is to compare two objects and if there's a match, add an attribute as a marker to the first ob ...

Tips for establishing optimal parameters for an object's dynamic property

I am working with an array of objects: export const inputsArray: InputAttributes[] = [ { label: 'Name', type: 'text', name: 'name', required: true }, { label: 'User name ...

Issue with MomentJS inBetween function consistently displaying incorrect results

I'm currently working on Vue Datatable and I have a specific requirement to search for records between two dates. I am using the moment.js library and the inBetween function to achieve this. Strangely, when I hardcode the dates, the function returns t ...

Tips for refreshing the page without losing the values of variables

In my simulation.jsp file, I have the following code that retrieves simulation data from a struts2 action: $(document).ready(function() { var data='<s:property escape="false" value="simInfos" />'; } Once I perform the simulation with this ...

Leverage cookies within a custom service in AngularJS

I attempted to implement angular cookies within a custom service, only to encounter the following error: Unknown provider: ngCookiesProvider <- ngCookies <- checkLoginService My approach involves storing modules, controllers, and services in separat ...

AngularJS routing not rendering the correct view

I'm encountering a routing problem with my AngularJS/ExpressJS application. The issue is that login.ejs and signup.ejs are partial views, while welcome.ejs serves as the main template. The intention is for these views to load in a ui-view container wi ...

Is the `visibility: hidden` property not functioning as expected?

I am trying to conceal the script for the photoset until it is fully loaded, but unfortunately the code below does not seem to be effective: JavaScript $('.photoset-grid').photosetGrid({ rel: $('.photoset-grid').attr("data-id"), gutte ...

What is the best way to trigger the Vue.js ApolloClient middleware to run again?

Within my main.js, I have implemented a code snippet that checks if a certain item exists in the localStorage. If it does, the code will add an Authorization header to the ApolloClient setup using middleware. However, if a new item is added to the localSt ...

Interactive image map with hover effects and external image swapping placed beyond the container

I've encountered a problem with a responsive image map and rollovers. Using Matt Stow's responsive image jQuery plugin ensures that coordinates are responsive, and clicking on an area brings up Lightview as expected. However, the issue arises whe ...

RegEx for constraining string length

I am attempting to identify all instances where the length of a string is more than 1. This is the regex I am using: string.match(/\B\w+(?=\w)/gi); I also attempted this approach: string.match(/^\B\w+(?=\w){2,}$/gi); Unfor ...

What is the reason that Gatsby's arrow function is unable to access a value from props that is calculated from a promise?

Could someone shed light on why the key value is showing as undefined within the arrow function: // in parent component const Parent = () => { const [key, setKey] = useState<string>(); // this contains an expensive function we on ...

I'm running into some issues with flexbox and I'm in need of some assistance to find

I positioned two divs next to one another, but instead of each taking up 100vw, they are both sharing 50% of the available space. Is there a solution for this issue? Thank you. Page Image import type { AppProps } from "next/app"; import "./global.cs ...

How to programmatically update one input value in AngularJS and trigger validation as if it was manually entered by the user?

I'm currently using Angular 1.3.0rc2 and facing an issue with setting one input field based on another input field after the blur event. When I try to set the value of an input field that only has a synchronous validator, everything works fine by usi ...

Guide to accessing the content within an h1 tag with JavaScript

I currently have a setup with 3 pages: 2 of them are WordPress pages while the other page is a custom page template featuring a form. The first two pages were created using the wp-job manager plugin. The first page includes a dropdown menu with a list of a ...

The custom attribute in jQuery does not seem to be functioning properly when used with the

I am currently working with a select type that includes custom attributes in the option tags. While I am able to retrieve the value, I am experiencing difficulty accessing the value of the custom attribute. Check out this Jsfiddle for reference: JSFIDDLE ...

Creating Layouts with Bootstrap 3

I'm exploring the codepen below in an attempt to mimic the appearance of the image provided consistently across all screen sizes. However, there are two issues that I am encountering - firstly, the green numbers on the first line which represent the d ...

Navigate through each file or image within a directory using Angular

I am facing a challenge with my app where each product has a gallery containing a random number of images, each with a completely unique name. These images are located in /src/assets/images/products/:id/. Currently, I am struggling to loop through and add ...

Sorting two different divisions is an example

I need advice on how to toggle between two divs, A and B, without having to reload the page. Ideally, I would like to have three buttons - one that shows only div A when clicked, another that displays only div B, and a third button that shows both A and ...

Creating responsive HTML page text and table with the use of JavaScript

Trying to create a responsive webpage has been a bit challenging. I experimented with height,style.height, style.OffsetHeight, etc. but still struggling to dynamically make a square table. Although the code below changes the height, the table's width ...