Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vue.js - Add or set new data to object in store

I'm trying to add or update an object to store with 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)
    }
  }
})

This returns state.userData.push is not a function.

And in the 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>

Later on I want to update userData with a value from other component, so that it impacts both components. I would like to have a nice way of adding, replacing, concating the old array with a new array. I followed the example in this video.

(FYI: I'm currently learning Vue.js from scratch and couldn't figure out this Vuex's mutations, actions...)

like image 959
Vincent Von Avatar asked Dec 15 '18 14:12

Vincent Von


2 Answers

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)
    }
  }
})

You are trying to use a push method of Object. Object does not have a push method you should initiate userData value with Array [] or assign that data to the object

like image 196
Gor Kotikyan Avatar answered Nov 14 '22 20:11

Gor Kotikyan


if you need reactivity:

mutations: {
  ADD_USER_DATA: (state, data) => {
    Object.keys(data).forEach( key => {
      Vue.set(state.userData, key, data[key])
    })
  }
like image 31
Zeitvertreib Avatar answered Nov 14 '22 22:11

Zeitvertreib