Working with an array of object in Vuex for form handling

Looking to make updates to a vuex store that includes an array of objects:

Users have a combobox for making selections, which then updates a property of the object in the database.

However, every time I choose an item from the autocomplete (combobox) I encounter the error message:

[vuex] do not mutate vuex store state outside mutation handlers.
. I'm unsure if this is allowed by vuex or if I need to adjust my approach.

I am currently using Nuxt, with an API built with express and a mongodb database.

This is my vuex setup:

State:

export default () => ({
  kivaferkoi: {
    picked: [],
    notYetPicked: []
  }
})

Mutations:

export default {
  fillKivaferkoi (state, data) {
    state.kivaferkoi = data
  },

  editPicked (state, data) {
    state.kivaferkoi.picked = data
  }
}

Actions:

import axios from 'axios'

export default {
  fetch (context, token) {
    return new Promise((resolve, reject) => {
      axios.get(process.env.api_url + '/kivaferkoi', {
        headers: {
          authorization: token
        }
      })
        .then((response) => {
          context.commit('fillKivaferkoi', response.data)
          resolve(response)
        }).catch((e) => {
         console.error(e)
          reject(e)
        })
    })
  },

  update (context, data) {
    const token = data.token
    delete data.token

    return new Promise((resolve, reject) => {
      axios.put(process.env.api_url + '/kivaferkoi/', data.value, {
        headers: {
          authorization: token
        }
      })
        .then((response) => {
          context.commit('editPicked', response.data)
          resolve(response)
        }).catch((e) => {
          console.error(e)
          reject(e)
        })
    })
  }
}

And here's my Vue component:

<template>
  <v-container>
    <v-row class="d-flex justify-center">
      <v-col cols="3">
        <v-card
          color="secondary"
          rounded="lg"
          flat
        >
          <v-card-title>
            Picked One
          </v-card-title>
          <v-card-text>
            <v-list color="secondary">
              <template v-for="(item, i) in picked">
                <v-list-item :key="i">
                  <v-list-item-avatar>
                    <v-img class="avatar" :src="item.avatar ? item.avatar : avatar" />
                  </v-list-item-avatar>
                  <v-list-item-content>
                    <v-list-item-title>
                      {{ item.name }}
                    </v-list-item-title>
                    <v-list-item-subtitle>
                      {{ item.surname }}
                    </v-list-item-subtitle>
                  </v-list-item-content>
                </v-list-item>
                <v-autocomplete
                  :key="'combobox' + i"
                  v-model="item.pickedSummary"
                  :items="prositSummary"
                  flat
                  solo
                  background-color="background"
                />
              </template>
            </v-list>
          </v-card-text>
        </v-card>
      </v-col>
    </v-row>
  </v-container>
</template>

<script>
export default {
  name: 'Kivaferoi',
  computed: {
    picked: {
      get () {
        return this.$store.state.kivaferkoi.kivaferkoi.picked
      },

      set (value) {
        this.$store.dispatch('kivaferkoi/update', { token: this.$auth.getToken('local', value) })
      }
    }
  }
}
</script>

Answer №1

One approach is to update information in the task with a duplicate (spread, for example, as shown below). In JavaScript, objects (as well as arrays) are assigned as references, so altering the selected array in any part of the code will also modify it in the database.

updateTaskInfo (state, newData) {
    state.task = {...newData}
  },

  modifySelected (state, newData) {
    state.task.selected = [...newData]
  }

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

Radio buttons with multiple levels

Looking to implement a unique two-level radio button feature for a specific option only. Currently, I have written a logic that will display additional radio buttons under the 'Spring' option. However, the issue is that when it's selected, t ...

Increase the identification of HTML element with jQuery

I've encountered an issue while trying to increment the id of 2 HTML elements, hwAddition and itemNumber, upon a button click event. The HTML code in question is as follows: <div id="hwAddition"> <div id="itemNumber" s ...

Creating an interactive Google line chart in MVC4

I am currently working on a dynamic line chart that needs to be able to adjust the number of lines (Standard, Latest, Earliest, Average) based on the database records. My code structure is similar to this example. function drawChart() { var data = ...

Form featuring a mandatory checkbox that must be selected in order to proceed; failure to do so will result in an

So here’s the situation: I have a form with a checkbox for agreeing to the terms of service, and I want to make sure it is checked before proceeding with the donation process. I only have the HTML code and no idea how to implement this functionality. Ide ...

State variables in React hooks like useState always return the previous value before

Whenever I choose a value, it seems to always display the previously selected option instead of the current one. What I really want is for the selection to update and store the current value immediately. const [postsPerPage, setPostsPerPage] = useState(1 ...

The REACT- Popover feature seems to be having trouble showing the data from my json file

Within the menu/ section, the names of my invited guests are not visible; only the InfoIcon is displayed in the cell. My goal is to implement a Popover feature that will show all the information about the invited guests (including their names and locations ...

What is the best way to verify and eliminate unnecessary attributes from a JSON request payload in a node.js application?

My goal is to verify the data in the request payload and eliminate any unknown attributes. Example of a request payload: { "firstname":"john", "lastname":"clinton", "age": 32 } Required attributes: firstname and lastname Optional a ...

Looking to showcase the outcome of the Procedure invocation when I made the call?

{ "isSuccessful": true, "resultSet": [ { "name": "pradeep", "password": 123, "timestamp": "2014-04-08T12:58:45.000Z" }, { "name": "dileep", "password": 1234, "timestamp": "2014-04-08T13:00:52.000Z" } ] } I have ...

Is there a way to search for multiple items using just one search term?

On my app, there is a search bar that currently only looks up data for one specific attribute. For example, if I type in "Hammer," it only searches for Tool names. Now, I need to expand the search functionality to accommodate different types of strings. F ...

`How can you generate navigation paths using the ngRoute module?`

I am currently working on creating a basic navigation system like the one illustrated below: html: <html ng-app="myapp"> <body> <ul> <li><a href="pages/sub1">sub1</a></li> <li><a href="pages/ ...

Having trouble with your Jquery resize or scroll function?

function adjustNavbar() { if ($(window).width() > 639) { $(document).scroll(function () { if ($(window).scrollTop() > 60) { $('.navbar').addClass('background', 250); } else { ...

How can you iterate over the input elements that are currently visible within a form using Javascript?

Is there a way to clear the values of all visible input fields in a form using JavaScript? I'm currently struggling with setting text inputs to empty as they come out as undefined. Any suggestions on how to achieve this? ...

Is it possible to use a marker with label in conjunction with a google maps circle?

In my mapping project, I use different markers for various scenarios. A regular marker represents an individual item, a customized marker represents a region containing multiple items, and a circle marker is used when there are too many items in one region ...

Try utilizing the array find() method in place of a traditional for loop

Is there a better way to refactor this code using the Array.find() method instead of nested for loops? onLoadTickets() { const ticketsReq = this.ticketService.getTickets(); const tariffsReq = this.tariffService.getTariffs(); forkJoin([ticketsR ...

Stop the form from being submitted using ajax if there are no values in the form fields

Having issues with a basic form. Struggling to prevent submission when fields are empty. Is there a straightforward way to validate the fields and stop the form from submitting? Below is the HTML form: <form method="post" name="simpleForm" id="simpleF ...

Is it possible for Vue to retrieve refs on mounted during nextTick following the dynamic import of the component?

Utilizing Nuxt js and Element UI, I have dynamically imported Element UI plugins in the plugins folder. export default () => { Vue.component("ElForm", () => import("element-ui/lib/form")); Vue.component("ElFormItem", ...

The steps to properly load "child.vue" into the correct position within "parent.vue" are as follows

Currently I am developing a single page web application using Vue.js. This app consists of 4 "page.vue" files, each with a right and left child .vue component nested inside. For instance, the Page1.vue file is structured as follows (omitting style and scr ...

The Ultimate Guide to Initializing Variables in UI Router State Access

In my application, I have defined 2 states. One is "tickets" which matches /tickets ... $stateProvider // defines the states of my application .state("tickets", { // assigns properties to each state url: "/tickets", // route templateUrl: "m ...

Learn how to implement pagination in AngularJS using the $http service

I need assistance in implementing pagination using Angularjs within the Ionic Framework. Can someone provide guidance on how to code pagination for fetching data from a JSON URL? controller.js angular.module('starter.controllers', []) .control ...

GTM - monitoring the most recent clicked element's input data

Custom Script function() { var inputs = document.getElementsByTagName("input"), selectedRadios = []; for (var i = 0;i < inputs.length;i++) { if(inputs[i].type==="checkbox" && inputs[i].checked) { selectedRadios.push(inputs[i].value); ...