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

The functionality of the AngularJS nested router is not functioning properly

I am encountering some challenges with Angular routing, specifically when using nested routes: The current 'abc' state works flawlessly for the route /admin/team/:teamId .state('admin', { url: '/admin', controller: & ...

While observing a camera in motion, the particles tinted by texture display sporadic flickering on WebGL and Three.js

Check out this jsfiddle I created to illustrate an issue with particles "flickering" when colored using a texture and the camera is moving. Update: The problem occurs even when there is no animation or movement on the particles. If you notice flickering o ...

Unable to access filteredItems from custom popup in uib-typeahead retrieval process

Issue with Retrieving Filtered Items from ng-repeat in Controller using $scope Despite trying to fetch filtered items from ng-repeat, the value of $scope.filteredItems appears as undefined when I log it to the console. I attempted to implement the solutio ...

Error: Angular does not recognize session storage reference

While my project is up and running, I have encountered an error in the terminal. let obj = { doc_id: sessionStorage.getItem('doc_id'), batch_no: sessionStorage.getItem('batch_no') } I attempted to make adjustments by a ...

Problem with single-table layout in DynamoDB and constraints on query parameters

I'm trying to limit the elements I fetch in each query, but encountered an issue: Using the single-table design in DynamoDB, I am only getting four items. If I check the first 10 elements in DynamoDB, I always get a count, regardless of my filtering ...

Fuzzy background when you scroll

My container has an image that blurs when you scroll down the page by 50 pixels. I feel like I've seen this effect somewhere before, but I can't quite recall where. I want the text to remain unaffected and not turn blue. Here is the HTML: <d ...

Find out whether the object is located behind another item

Is there a method to determine if elementA is "obscured" by another element, meaning it is not visible to the user? We could potentially achieve this using stacking context, but the challenge lies in identifying which elements to compare. This would requi ...

Tips for restricting function invocations in JavaScript?

I am seeking a function called limitCalls(fn, maxCalls) which accepts a function fn and creates a new function that can only be called the specified number of times in maxCalls. Here is a test example: it('limitCalls', () => { const makeIncre ...

Is it necessary to define module.exports when using require() to import a file?

While setting up my Express server, I am using Babel to transpile my ES6 files seamlessly. In my vanilla JS server.js file, I include require('babel-core/register') and require('./app'). Within my ES6 file app.js, I handle all the usua ...

Exploring ways to access global window variables in React using JavaScript

I've been following the discussion on how to transfer variables from JavaScript to ReactJS. Here is my array of objects in JavaScript: window.dataArr = []; function makeJsObj(descr, currDate, done) { var data = {}; console.log(descr ...

Comparing Two Arrays in AngularJS and Disabling on Identical Cases

I currently have two tables: "Available subject" and "Added subject" which are populated by ng-repeat with two separate lists of objects. My objective is to accomplish three things: 1 - When the user clicks on the plus sign, a row with identical content s ...

Guide to updating a database using ajax and javascript in asp.net mvc without the need to refresh the page

Is there a way to update the value of an enumdropdownlist from "active" to "inactive" in my database through an ajax call without having to refresh the page? I am unsure whether to use a javascript method or ajax.beginform for this task. I attempted to us ...

Converting information from a model into individual variables

I'm a newcomer to typescript and angular, and I've been attempting to retrieve data from firebase using angularfire2. I want to assign this data to variables for use in other functions later on. I am accustomed to accessing object members using d ...

What is the best way to determine if a jQuery AJAX response contains HTML elements?

On my webpage, I have a single form that triggers an AJAX call which can result in two different responses. One of the responses only includes a status code. In order to display any HTML contents returned by the response object on my page, I need to exami ...

What causes these queries to function separately but fail when combined?

I am facing an issue with combining 2 queries in my Firestore collection. These are the 2 examples that work: database .collection('servicebonnen') .where('medewerker', '==', 'CEES') and: database .collecti ...

Guide on transferring a JWT token to a Node.js backend

Recently, I developed a node.js server featuring a login system and am focused on safeguarding my routes. Despite creating middleware to authenticate each protected route, I keep encountering an "Authentication failed" message after logging in. How can I e ...

Getting the response from Google Cloud Translate API using Node JS

Recently, I've been experimenting with the Google Cloud Translate API in NodeJS. While I am able to successfully console.log the value returned from a promise, I am facing challenges passing that value into an EJS template file. Whenever I try to disp ...

The offset values of $(element) keep increasing indefinitely when they are updated repeatedly

After researching how to utilize JavaScript drag functionality to move elements, the goal is to dynamically adjust the cursor position within a square when dragged. In an attempt to simplify the process and avoid storing x and y offsets as separate variabl ...

What is the process for attaching an analytics tag to data messages using the Firebase Admin SDK with Javascript or TypeScript?

Adding a label to my message is something I'm trying to do. I checked out the official guidelines here and found a similar question answered on Stack Overflow here. I've been attempting to implement this in JavaScript, but I'm stuck. Here& ...

Storing information using ajax and json technologies

I've inherited a project where I need to work on saving data to the database using an input. The function responsible for this (SaveData) is not functioning properly. Since I'm not very familiar with ajax and json, can someone please help me iden ...