javascriptvue.jsnuxt.jsvuex

Getting mutation error in Nuxt JS while binding form with state


I am trying to bind my form's fields with my vuex store in Nuxt JS. It works fine with normal text fields with get() set() in computed. But having trouble in customizing getting and setting manually. I am trying to push objects to an array in a specific format from my template to store and also keep the binding among them. Here is my code:

<template>
  <div class="container setting-form-area-business">
    <b-form-group v-for="(input, index) in phoneNumbers" :key="`phoneInput-${index}`">
      <label>Mobile Number {{index+1}}*</label>
      <b-input-group>
        <b-form-input v-model="input.phone" @input="updateStore" class="custom-form-input-business">
        </b-form-input>
        <b-input-group-append v-show="phoneNumbers.length > 1">
          <b-button class="mobile-number-remove-btn" @click="removeField(index, phoneNumbers)"></b-button>
        </b-input-group-append>

      </b-input-group>

    </b-form-group>

    <b-form-group>

      <b-button class="jh-btn2" @click="addField">Add More Mobile Number</b-button>

    </b-form-group>

  </div>
</template>
<script>
  export default {
    props: [
      'visited'
    ],

    data() {
      return {
        phoneNumbers: this.$store.state.business.formvalue.mobileNumber.length ? this.$store.state.business.formvalue
          .mobileNumber : [{
            phone: ""
          }],


      }
    },
    computed: {
      mobilenumbers() {
        return this.$store.state.business.formvalue.mobileNumber
      },

    },
    methods: {

      addField() {
        this.phoneNumbers.push({
          value: ""
        });

      },
      removeField(index, fieldType) {

        fieldType.splice(index, 1);
        console.log('fieldType', fieldType);
        this.emitErrorStatus();
      },
      updateStore() {
        this.$store.commit('business/setformmobileNumber', {
          mobileNumber: this.phoneNumbers
        })
      }
    },
  }

</script>

this was working fine when I was in vue, but coming to nuxt, it is giving me error

[vuex] do not mutate vuex store state outside mutation handlers.


Solution

  • As told by the error, you should not mutate the state. There are several ways to handle this one. A quick search here could give you a lot of answers.

    This is mine (using Lodash's cloneDeep): https://stackoverflow.com/a/66262659/8816585