0

I just want to edit and save content from json

Following the next question I use deep clone to clone my data and edit in the computed object than sent it to the central object on Vuex

The code works just for the first time, I can edit the data and after press edit it changes the data... but if I try to edit again... I get the error

[Vue warn]: Error in callback for watcher "function () { return this._data.$$state }": "Error: [vuex] do not mutate vuex store state outside mutation handlers."

component.js

<template>
  <div class="hello">
    <form @submit.prevent="saveForm();">
      <input type="text" v-model="contentClone.result" />
      <button type="submit">edit</button>
      <p>{{ contentClone.result }}</p>
    </form>
  </div>
</template>

<script>
export default {
  name: "HelloWorld",
  data() {
    return {
      content: {},
      contentClone: {}
    };
  },

  methods: {
    saveForm(event) {
      this.$store.dispatch("UPDATE_CONTENT", this.contentClone);
    }
  },

  beforeMount() {
    this.contentClone = JSON.parse(this.contentState);
  },

  computed: {
    contentState() {
      return JSON.stringify({ ...this.$store.getters["getContent"] });
    }
  }
};
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
h1,
h2 {
  font-weight: normal;
}
ul {
  list-style-type: none;
  padding: 0;
}
li {
  display: inline-block;
  margin: 0 10px;
}
a {
  color: #42b983;
}
</style>

store.js

import {
  UPDATE_CONTENT
} from "../actions/user";
import Vue from "vue";

const state = {
  content: { result: "original content" },
  status: String,
  errorMessage: []
};

const getters = {
  getContent: state => state.content
};

const actions = {
  [UPDATE_CONTENT]: ({ commit }, payload) => {
    commit(UPDATE_CONTENT, payload);
  }
};

const mutations = {
  [UPDATE_CONTENT]: (state, payload) => {
    Vue.set(state, "content", payload);
  }
};

export default {
  state,
  getters,
  actions,
  mutations
};

I replicated the error in the link above, https://codesandbox.io/s/p7yppolw00

if I could just restart the content in the component after saving it, I think that might fix the error

Marcogomesr
  • 2,614
  • 3
  • 30
  • 41

1 Answers1

0

You are saving an object this.contentClone as state, which is further bound with input and this makes input able to directly makes changes to your vuex store through v-model and hence the error; A simple fix would be clone this.contentClone when dispatch it to vuex state:

saveForm(event) {
  this.$store.dispatch("UPDATE_CONTENT", JSON.parse(JSON.stringify(this.contentClone)));
}

Or IMO a better solution would be to dispatch the result as a string instead of using an object. See the working example: https://codesandbox.io/s/mmpr4745z9

Psidom
  • 209,562
  • 33
  • 339
  • 356