Updating the Vuex store with new information or setting data in an object

I'm currently struggling with adding or updating an object in the store using Vuex.

import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    userData: {}
  },
  mutations: {
    ADD_USER_DATA: (state, data) => {
      state.userData.push(data)
    }
  }
})

However, I keep encountering the error message saying state.userData.push is not a function.

In my components:

<template>
  <div>
    <input type="date" v-model="inputData.date1">
    <input type="date" v-model="inputData.date2">
    <input type="number" v-model="inputData.date3">
    <button @click="submitForm">Submit</button>
  </div>
</template>

<script>
import { mapState, mapMutations } from 'vuex'

export default {
  data () {
    return {
      inputData: {}
    }
  },

  computed: {
    ...mapState([
      'userData'
    ])
  },

  methods: {
    ...mapMutations([
      'ADD_USER_DATA'
    ]),
    submitForm () {
      this.ADD_USER_DATA(this.inputData)
    }
  }
}
</script>

Furthermore, I aim to update the userData with a value from another component so that both components are affected. I am looking for an efficient way to add, replace, or concatenate the old array with a new one. I tried following the demonstration provided in this video.

(Just a heads up: I am still new to learning Vue.js and finding it challenging to understand Vuex's mutations and actions...)

Answer №1

import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    // userData: {}
    userData: []
  },
  mutations: {
    ADD_USER_DATA: (state, data) => {
      state.userData.push(data)
    }
  }
})

If you are attempting to use the push method on an object, please note that objects do not have a push method. To resolve this, make sure to initialize the userData value as an array [], or assign the data directly to the object.

Answer №2

For those who require responsiveness:

alterations: {
  ADD_USER_INFORMATION: (content, data) => {
    Object.keys(data).forEach( key => {
      Vue.set(content.userData, key, data[key])
    })
  }

Answer №3

I decided to utilize the Object.assign technique.

  changes: {
    ADD_DATA_USER: (state, data) => {
      // state.dataUser.assign(data)
      state.dataUser = Object.assign({}, data)
    }
  }

Answer №4

Give it a shot

import React from 'react'
import { Provider } from 'react-redux'
import store from './store'

ReactDOM.render(
  <Provider store={store}>
    <App />
  </Provider>,
  document.getElementById('root')
);

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 Directional and Spotlight Lighting with ThreeJS Helper Functions

I am currently utilizing a guide on implementing light in Threejs from Light in Threejs. I have successfully added some light to my scene. Now, I am attempting to add light to the character in my game but it is still not working. Even though I used the co ...

Struggling to connect API from React and Node using a proxy server

I have encountered a troubleshooting issue with React and Node that I am struggling to resolve. The problem lies in the communication between my node server and coinmarketcap API. While I successfully receive data from both endpoints (all coins and individ ...

Getting the value of "Page=?" from the href attribute in an HTML tag can be done using Selenium Webdriver and Java

I am looking to extract the value "page = ?" from a specific "href" tag in the HTML code below. I need this value for my Selenium WebDriver script so that my loop can iterate up to page 53. Can someone guide me on how to retrieve the "page =" value mentio ...

Transmitting information following successful password verification

Currently, I am working on a form to insert users into a database. Along with this, I have two scripts in place - one for password validation and the other for AJAX retrieval of PHP results. As of now, these two scripts are functioning independently. How ...

Difficulty in showcasing error on the website with JavaScript

I have recently developed a webpage that includes several input boxes and a submit button within a form as shown below: <form action="" method="post" name="password"> Upon clicking the submit button, a JavaScript function is triggered to validate i ...

Design a progress bar that advances in increments of at least two and up to a maximum of

My task involves managing a simple list. const [progressBar, setProgressBar] = useState([ { isActive: false, name: "step1" }, { isActive: false, name: "step2" }, { isActive: false, name: "step3" }, { isActive ...

Challenges when utilizing the command "npm install" within a programmatic context

I'm really excited about the potential of using "npm programmatically," but I've hit a roadblock. The function "npm.load" doesn't seem to be triggering for me. None of the console logs inside of my "npm.load" or "npm.commands.install" functi ...

In Three.js r74, JSONLoader mistakenly links a duplicate of all geometry to the initial bone

I have gained more insight into the bug, so I am rewriting this question. It seems that when using the JSONLoader in r74, the first named bone in an exported Maya scene ends up with a duplicate of all the geometry. EDIT: Check out this JSFiddle for refere ...

Ways to transfer property values between two instances of a component

Two datepicker components are present, one for "From" date and another for "To" date. If the "To" date is empty, I want to automatically update it with the value from the "From" date. I have considered using 'emit' on the value but I am unsure ...

What is the best way to integrate ES6 ReactJS code into an Express application?

I am trying to initially render my ReactJS application on the server using ExpressJS. Although I have been able to import ES6 modules using require(), the module crashes upon loading because it contains ES6 code (ES6 import and export). Index Route var ...

I'm wondering why my socket.io emit isn't triggering a content update

While working on adapting the IBM angularjs tutorial here into a Yeoman angular-fullstack tutorial, I encountered a slight issue. In my version, when I vote on a Poll, the data does not refresh to display the results. I have tried extensively debugging it ...

Adjust the size at the location of the cursor

I am having trouble understanding how to implement zoom based on mouse position using this example here: (https://stackblitz.com/edit/js-fxnmkm?file=index.js) let node, scale = 1, posX = 0, posY = 0, node = document.querySelector('.f ...

Storing API data in localStorage using VueJS: A step-by-step guide

As I work on practicing building a simple SPA with VueJS, one of my current tasks involves listening to an API and storing certain data in the browser's localStorage. However, my experience with VueJS is still limited, so I'm unsure about how to ...

Updating the route path for version control in Express.js

When working with an ExpressJS application, the following paths should be considered: GET /v1/users/detail GET /v2/users/detail The corresponding routers are as follows: // v1/users.js router.get('/v1/users/detail', (req, res, next) => res. ...

Creating Tree diagrams with pie charts using D3

Has anyone tried creating a D3 pie component within each node of a tree? I've managed to build the tree and a single pie separately, but I'm struggling to combine them. My JSON data looks like this: window.json = { "health": [{ "value" ...

What is the best way to customize the appearance of an XML snippet using Greasemonkey?

I am attempting to customize an XML fragment retrieved from a server response using a Greasemonkey script. Take a look at this sample XML fragment from w3schools.com: <note> <to> Tove</to> <from>Jani</from> <heading ...

Vue.js | Web scrapers struggle to track v-for generated URLs

I am currently managing a small website that utilizes Laravel and Vue.js to display a list of items. You can check it out here. It seems like the Google crawler is having trouble following the links generated by the v-for function. In my Google Search Con ...

Why does my counter keep incrementing by more than one every time?

As I work on creating a test in jQuery, I've encountered an issue with my counter variable count. It seems to increase by more than one when the correct answer is used. function nextQuestion(){ $('#submit').show(); $('#next&apo ...

Tips for maintaining retrieved data when parameters are updated on the preceding page in Nuxt framework

Is there a way to maintain the data received from "/about/1" when transitioning to "/about/2" without remounting the component? Currently, when the route parameter changes using [/about/:page]this.$route.params.page, the component is remounted causing the ...

Playing audio from local blob data is not supported on mobile browsers

I'm trying to stream blob data in mp3 format, but I'm experiencing difficulties with mobile browsers. The code below works perfectly on PC browsers, but not on mobile: // Javascript var url = URL.createObjectURL(blob); audio = document.getEleme ...