What would be the most effective approach for creating a reactive setter for an object within an array in Vuex?

I am working with a Vuex object that contains an array of languages consisting of objects with guid, name, and level properties.

I am trying to figure out how to write a method that will make it reactive. Currently, I have an input field with a value of "language.name" and I am unsure of the best practice for writing the method for the @input event.

This is how my Vuex store looks:

const state = () => ({
  ...
  obj: {
    skills: [],
    languages: []
  },
  ...
})

Here is an example of how it is used in the template with

v-for="(language, index) in obj.languages"
:

v-text-field(
  :value="language.name"
  @input="setLanguage"
)

After researching getters, setters, modern JavaScript limitations for Vue, and the need to use Vue.set() to track changes in an array, I have come up with the following solution based on the TodoMVC example on the Vuex GitHub:

setLanguage: (e) => {
  function updateLanguage({language, guid = language.guid, name = language.name, level = language.level}){
    Vue.set(this.$store.state.obj.languages, this.$store.state.obj.languages.findIndex((it) => it.guid === guid), {guid, name, level})
  }
  const name = e.target.value.trim()
  const language = this
  updateLanguage({language, name})
}

However, I am not satisfied with this solution and feel like I am missing some key concepts.

Can someone suggest the best practice for making reactive objects within an array in Vuex state?

Answer №1

When working with vuex, it is recommended to utilize actions and mutations.

setLanguage: (e, index) => {
  let name = e.target.value.trim()
  this.$store.dispatch('setLanguage', {name, index}) //triggers a vuex action
}

Next step is to create an action:

setLanguage({ commit }, payload) {
  commit('setLanguage', payload) //implements a vuex mutation
}

Lastly, define a mutation:

setLanguage(state, payload) {
  state.languages[payload.index].name = payload.name
}

Refer to the vuex documentation for more information: https://vuex.vuejs.org/guide/actions.html

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

Utilizing Vuejs within Laravel's blade templates

Hey there, I'm looking to create a dormitory management system using Laravel and Vue.js. I need help figuring out how to display my data using a Vue component instead of the "welcome.blade.php" file in Laravel. I am utilizing API routes for this proje ...

developing a dynamic map with javascript

In the image provided, my concept is for it to initially be without a green tint. However, when the user hovers over specific areas, they would turn green and become clickable links. There are multiple areas in the image, with this being just one example. ...

The issue arises when a continuous use of angularjs directives linked with an external template fails to display correctly upon the addition of new

In the code snippet below, you'll find a fiddle that displays 3 columns of numbers that increase in value. These columns represent directives with different templates: one inline, one preloaded, and one from an external template. When you click on the ...

Choosing a specific category to display in a list format with a load more button for easier navigation

Things were supposed to be straightforward, but unexpected behaviors are popping up all over the place! I have a structured list like this XHTML <ul class = "query-list"> <li class="query"> something </li> <li class="query" ...

Manipulating a textarea in jQuery by inserting a string and selecting a specific portion of it

Just as seen on SO with the B button: **bold text** Including that bold text is automatically highlighted and the cursor is placed right before the b ...

Why is it that GetElements does not provide immediate results upon execution?

Just diving into the world of Javascript for the first time and experimenting with it on Chrome, but running into unexpected results. When I try: document.getElementsByTagName("h1") I anticipate seeing: <h1>tester h1 in body</h1> Instead, wh ...

JavaScript is abstaining from generating a div element

I've been struggling for the last couple of hours to create a special div element with specific properties, but no matter what I try, it just won't work. Can someone please point out where I'm going wrong? function generateRoundDiv() { var ...

Determining the state of a button based on a property's values

Is it possible to conditionally display a button based on the value of the sendSMS property of the logged-in user in AngularJS? How can I achieve this using ng-show in the HTML? I'm uncertain if I correctly assigned the value for the sendSMS property ...

Could the act of one function updating state and another immediately accessing it lead to a potential race condition occurring?

I am faced with a scenario where I have two components - one for uploading files and the other for submitting a form. Each component has its own callback function that needs to trigger a backend request once completed. My objective is to ensure that the ba ...

What could be causing the tooltip to appear in the wrong position

It may seem like a trivial issue, but I am struggling to get my tooltips to display in the correct position. No matter what I try, they always appear off position. I have searched for solutions and attempted to rearrange the order of scripts, add new scri ...

Find the furthest distance from the average in a set of data points and identify the corresponding data point

Imagine having an array of data structured like this: var data = [{name: "craig", value: 10}, {name: "oliver", value: 15}] My goal is to create a function that can accept parameters like: function findExtremeValue(windowSize, pointsToTake, data, valueAc ...

Having issues retrieving a JSON array in PHP with the json_decode function

Can someone assist me with passing and returning an array to a PHP script? I have successfully tested the json_encode portion, but I am facing issues with the json_decode on the PHP side. Javascript scid_list = []; $('.filter_on').each ...

How can I align a button right next to the table row data in HTML using Bootstrap?

Is there a way to add a button next to the table data in each row without a border? I attempted to create a new column for the button, but the border interferes with the design. I am using Bootstrap 4 for this project. Here is the HTML code: <div cl ...

Extracting Vertices, Edges, Faces, and Triangles from GLB Model Using ThreeJS GLTFLoader

I am looking to incorporate basic information about the model into my model viewer. Specifically, I need to obtain the vertex, edge, face, and triangle count of the object, or at the very least, the vertex count. My attempted approach involves using the f ...

Encountering problem while exhibiting server's response message within a modal popup in Angular 6

I have implemented two custom dialog modals in an Angular component. The objective is to open the appropriate modal and display the response message. The component receives two values as Observables from my services: The name of the modal that needs to ...

Utilizing ng-repeat, ng-grid, and ng-click in Angular: A comprehensive guide

I'm encountering an issue with populating a table using ng-repeat after a cellTemplate ng-click. cellTemplate: '<div ng-click="foo()" ng-bind="row.getProperty(col.field)"></div>' Within this foo method, I am tryi ...

Determine the TR id when a button within a TD element is clicked using JavaScript/jQuery

Currently seeking a method to generate a unique identifier for use as a parameter in a JavaScript function. Specifically interested in extracting the id of the first td element if feasible. <tr id='it'><td id="#nameiron">Jason</td ...

What is the correct way to execute a jQuery trigger on a checkbox or radio button to simulate a user clicking on it?

My current page utilizes can.js, making it challenging to replicate the issue on jsfiddle.net. The result I am experiencing is as follows: When I click on a checkbox (or even a radio button), an input text box should update accordingly (for example, displ ...

Using AngularJS in conjunction with other scripts

I am currently working on an application and now I have the task of implementing a dynamic menu using AngularJS. This requires me to modify variables in the AngularJS application from my existing code. Here is the example I am experimenting with: <scr ...

What is the process for entering a value into mysql based on the date?

Seeking assistance with a specific coding challenge. The task at hand involves inputting a date, such as '2018-05-08', and based on the user's input, storing the value in different columns of a database table. For instance, if the date is &a ...