Jake Anderson
Jake Anderson

Reputation: 321

Vuex: Prevent input fields from updating the state/store

In my Vuex app, I have an update form which pre-populates the input fields with the users credentials (from the Vuex store), then on submission submits the form to the datasource.

So I need to display the users details on the page, but don't want them to be updated (reactively) when the users is changing the values in the form, as in my case it's be misleading if the user dose not complete the form leaves the page and comes back to it. Then it may look like the data has been updated (which is hasn't as they are yet to submit the form).

Heres a snippet of my code:

Form (HTML):

<input
  v-model.trim="userProfile.name"
  :value="userProfile.name"
  type="text" >
</input>

<input
  v-model.trim="userProfile.position"
  :value="userProfile.position"
  type="text" >
</input>

<div>
  {{ userProfile.name }} {{ userProfile.position }}
</div>

And the Vue code:

computed: {
  ...mapState(["userProfile"]),
},
methods: {
  updateProfile() {
    this.$store.dispatch("updateProfile", {
      name: this.name !== "" ? this.name : this.userProfile.name,
      position: this.position !== "" ? this.position : this.userProfile.position,
    })
  }
},

Just to clarify this code works fine, the issue for me is that i don't want the {{ userProfile.name }} {{ userProfile.position }} to be reactive and only update once the form has been submitted.

Upvotes: 0

Views: 584

Answers (1)

Andrew Vasylchuk
Andrew Vasylchuk

Reputation: 4779

The answer is to init your initial data with that values from the store.

export default {
  ...
  data() {
    const localUserProfile = JSON.parse(JSON.stringify(this.store.state.userProfile))

    return {
      localUserProfile
    }
  },
  ...
}
<input
  v-model.trim="localUserProfile.name"
  type="text" >
</input>

<input
  v-model.trim="localUserProfile.position"
  type="text" >
</input>

<div>
  {{ userProfile.name }} {{ userProfile.position }}
</div>

Notice: you should create independent copy of your store.state.userProfile, to do that you can use JSON.parse(JSON.stringify(this.store.state.userProfile)) or lodash.clonedeep.

Don't forget to update your store with values from localUserProfile in your updateProfile method.

Also your code has some errors:

  1. You can not mutate the state of the store directly using v-model="userProfile.name". Probably you have errors in your console.

Upvotes: 2

Related Questions