Search code examples
vue.jsvuexvue-routerapollo

Vuex state changing with mutation - apollo graphql query


I have a form where the user edits the object - in my case, metadata about a story - after it is loaded from GraphQL. However, when I use my vue-router guard to check if the story has been changed, the story state is always the modified value.

Vuex story.js

...
  getters: {
    ...formSubmit.getters,
    getStory: (state) => {
     return  state.story},
    getEditedStory: (state) => state.editedStory,
    getStoryDescription: (state) => {
      return state.story.description
    }
  },
  mutations: {
    ...formSubmit.mutations,
    setStory(state, payload) { 
      state.story = payload 
    },
    setEditedStory(state, payload) { 
      state.editedStory = payload 
    }
  },
...

Form component

   export default {
   ...
   apollo: {
      story: {
        query: gql`query GetStory($id: ID!) {
          story(id: $id) {
            name
            summary
            description
          }
        }`,
        variables() {
          return {
            id: this.id
          }
        },
        result({ data}) {
          this.setText(data.story.description)
          this.setStory(data.story)
          this.setEditedStory(data.story)
        },
      }
    },
...

In my form I have the values mapped with v-model:

    <v-text-field 
        v-model="story.name"
        class="mx-4"
        label="Add your title..."
        single-line
        :counter="TITLE_TEXT_MAX_LENGTH"
        outlined
        solo
        :disabled="updateOrLoadInProgress"
      />

However, for some reason whenever I call this.getStory its value is modified accordingly to the v-model. Why?


Solution

  • Although I still don't quite understand why, it seems like the changes to the apollo variable story affect the store.story values with using the mutations to set them.

    I've modified the initial setters to be like this:

              this.setText(data.story.description)
              let loadedStory = {
                name: data.story.name,
                description: data.story.description,
                summary: data.story.summary,
              }
              this.setStory(loadedStory)
              this.setEditedStory(data.story)
            },
    

    which seems to prevent the state.story from following the changes to the apollo created story variable. This seems like unexpected behaviour, and I don't quite understand what part of javascript object assignment makes this work this way.