Setting value to input field using Vuex store modules





.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty{ height:90px;width:728px;box-sizing:border-box;
}







0















I have a vuex in module mode that fetching the data of a user:



store/modules/users.js



import axios from "axios";

export const state = () => ({
user: {}
});

// Sets the values of data in states
export const mutations = {
SET_USER(state, user) {
state.user = user;
}
};

export const actions = {
fetchUser({ commit }, id) {
console.log(`Fetching User with ID: ${id}`);
return axios.get(`${process.env.BASE_URL}/users/${id}`)
.then(response => {
commit("SET_USER", response.data.data.result);
})
.catch(err => {
console.log(err);
});
}
};

// retrieves the data from the state
export const getters = {
getUser(state) {
return state.user;
}
};


then on my template pages/users/_id/index.vue



<b-form-input v-model="name" type="text"></b-form-input>

export default {
data() {
return {
name: ""
}
},
created() {
// fetch user from API
this.$store.dispatch("fetchUser", this.$route.params.id);
}
}


Now I check the getters I have object getUser and I can see the attribute. How can I assign the name value from vuex getters to the input field?










share|improve this question





























    0















    I have a vuex in module mode that fetching the data of a user:



    store/modules/users.js



    import axios from "axios";

    export const state = () => ({
    user: {}
    });

    // Sets the values of data in states
    export const mutations = {
    SET_USER(state, user) {
    state.user = user;
    }
    };

    export const actions = {
    fetchUser({ commit }, id) {
    console.log(`Fetching User with ID: ${id}`);
    return axios.get(`${process.env.BASE_URL}/users/${id}`)
    .then(response => {
    commit("SET_USER", response.data.data.result);
    })
    .catch(err => {
    console.log(err);
    });
    }
    };

    // retrieves the data from the state
    export const getters = {
    getUser(state) {
    return state.user;
    }
    };


    then on my template pages/users/_id/index.vue



    <b-form-input v-model="name" type="text"></b-form-input>

    export default {
    data() {
    return {
    name: ""
    }
    },
    created() {
    // fetch user from API
    this.$store.dispatch("fetchUser", this.$route.params.id);
    }
    }


    Now I check the getters I have object getUser and I can see the attribute. How can I assign the name value from vuex getters to the input field?










    share|improve this question

























      0












      0








      0








      I have a vuex in module mode that fetching the data of a user:



      store/modules/users.js



      import axios from "axios";

      export const state = () => ({
      user: {}
      });

      // Sets the values of data in states
      export const mutations = {
      SET_USER(state, user) {
      state.user = user;
      }
      };

      export const actions = {
      fetchUser({ commit }, id) {
      console.log(`Fetching User with ID: ${id}`);
      return axios.get(`${process.env.BASE_URL}/users/${id}`)
      .then(response => {
      commit("SET_USER", response.data.data.result);
      })
      .catch(err => {
      console.log(err);
      });
      }
      };

      // retrieves the data from the state
      export const getters = {
      getUser(state) {
      return state.user;
      }
      };


      then on my template pages/users/_id/index.vue



      <b-form-input v-model="name" type="text"></b-form-input>

      export default {
      data() {
      return {
      name: ""
      }
      },
      created() {
      // fetch user from API
      this.$store.dispatch("fetchUser", this.$route.params.id);
      }
      }


      Now I check the getters I have object getUser and I can see the attribute. How can I assign the name value from vuex getters to the input field?










      share|improve this question














      I have a vuex in module mode that fetching the data of a user:



      store/modules/users.js



      import axios from "axios";

      export const state = () => ({
      user: {}
      });

      // Sets the values of data in states
      export const mutations = {
      SET_USER(state, user) {
      state.user = user;
      }
      };

      export const actions = {
      fetchUser({ commit }, id) {
      console.log(`Fetching User with ID: ${id}`);
      return axios.get(`${process.env.BASE_URL}/users/${id}`)
      .then(response => {
      commit("SET_USER", response.data.data.result);
      })
      .catch(err => {
      console.log(err);
      });
      }
      };

      // retrieves the data from the state
      export const getters = {
      getUser(state) {
      return state.user;
      }
      };


      then on my template pages/users/_id/index.vue



      <b-form-input v-model="name" type="text"></b-form-input>

      export default {
      data() {
      return {
      name: ""
      }
      },
      created() {
      // fetch user from API
      this.$store.dispatch("fetchUser", this.$route.params.id);
      }
      }


      Now I check the getters I have object getUser and I can see the attribute. How can I assign the name value from vuex getters to the input field?







      vue.js nuxt.js vuex-modules






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Jan 3 at 9:06









      Allen ChunAllen Chun

      1,6921937




      1,6921937
























          2 Answers
          2






          active

          oldest

          votes


















          2














          watcher is probably what you need



          export default {
          // ...
          watch: {
          '$store.getters.getUser'(user) {
          this.name = user.name;
          },
          },
          }





          share|improve this answer



















          • 1





            Nice I made it work. Thanks Jacob, in what lifecycle should I call the dispatch? Right now I'm calling it from beforeCreate()

            – Allen Chun
            Jan 3 at 9:38











          • There's no hard rules for this. Normally I do it in created. forum.vuejs.org/t/…

            – Jacob Goh
            Jan 3 at 9:41











          • I think that this use case calls for a computed property instead of a watcher

            – Frank
            Jan 3 at 9:41













          • @AllenChun i think this is what Frank means. Not sure if it is what you want though. vuex.vuejs.org/guide/forms.html#two-way-computed-property

            – Jacob Goh
            Jan 3 at 9:44











          • @JacobGoh Please check my answer. Regardless of whether you want a two-way binding you should use a computed property over watcher.

            – Frank
            Jan 3 at 9:50





















          0














          While Jacob's answer isn't necessarily incorrect, it's better practice to use a computed property instead. You can read about that here



            computed: {
          user(){
          return this.$store.getters.getUser
          }
          }


          Then access name via {{user.name}} or create a name computed property



            computed: {
          name(){
          return this.$store.getters.getUser.name
          }
          }


          Edit: fiddle as example https://jsfiddle.net/uy47cdnw/



          Edit2: Please not that if you want to mutate object via that input field, you should use the link Jacob provided.






          share|improve this answer





















          • 1





            in some cases, you would be very right. I just don't think this is the case here. v-model="name" combine with a computed property without setter is going to be problematic. (god... i feel offended by the unreasonable downvote )

            – Jacob Goh
            Jan 3 at 9:59













          • Initially my approach is using computed property but I need to mutate the object using input field, then I have 10 fields in my form so I find computed property really tedious. There's also an instance I used computed property to set the state and when I refreshed the page the value suddenly gone.

            – Allen Chun
            Jan 3 at 10:02











          • @JacobGoh Alright, i see your point.

            – Frank
            Jan 3 at 10:03












          Your Answer






          StackExchange.ifUsing("editor", function () {
          StackExchange.using("externalEditor", function () {
          StackExchange.using("snippets", function () {
          StackExchange.snippets.init();
          });
          });
          }, "code-snippets");

          StackExchange.ready(function() {
          var channelOptions = {
          tags: "".split(" "),
          id: "1"
          };
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function() {
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled) {
          StackExchange.using("snippets", function() {
          createEditor();
          });
          }
          else {
          createEditor();
          }
          });

          function createEditor() {
          StackExchange.prepareEditor({
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader: {
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          },
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          });


          }
          });














          draft saved

          draft discarded


















          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54019154%2fsetting-value-to-input-field-using-vuex-store-modules%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown

























          2 Answers
          2






          active

          oldest

          votes








          2 Answers
          2






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          2














          watcher is probably what you need



          export default {
          // ...
          watch: {
          '$store.getters.getUser'(user) {
          this.name = user.name;
          },
          },
          }





          share|improve this answer



















          • 1





            Nice I made it work. Thanks Jacob, in what lifecycle should I call the dispatch? Right now I'm calling it from beforeCreate()

            – Allen Chun
            Jan 3 at 9:38











          • There's no hard rules for this. Normally I do it in created. forum.vuejs.org/t/…

            – Jacob Goh
            Jan 3 at 9:41











          • I think that this use case calls for a computed property instead of a watcher

            – Frank
            Jan 3 at 9:41













          • @AllenChun i think this is what Frank means. Not sure if it is what you want though. vuex.vuejs.org/guide/forms.html#two-way-computed-property

            – Jacob Goh
            Jan 3 at 9:44











          • @JacobGoh Please check my answer. Regardless of whether you want a two-way binding you should use a computed property over watcher.

            – Frank
            Jan 3 at 9:50


















          2














          watcher is probably what you need



          export default {
          // ...
          watch: {
          '$store.getters.getUser'(user) {
          this.name = user.name;
          },
          },
          }





          share|improve this answer



















          • 1





            Nice I made it work. Thanks Jacob, in what lifecycle should I call the dispatch? Right now I'm calling it from beforeCreate()

            – Allen Chun
            Jan 3 at 9:38











          • There's no hard rules for this. Normally I do it in created. forum.vuejs.org/t/…

            – Jacob Goh
            Jan 3 at 9:41











          • I think that this use case calls for a computed property instead of a watcher

            – Frank
            Jan 3 at 9:41













          • @AllenChun i think this is what Frank means. Not sure if it is what you want though. vuex.vuejs.org/guide/forms.html#two-way-computed-property

            – Jacob Goh
            Jan 3 at 9:44











          • @JacobGoh Please check my answer. Regardless of whether you want a two-way binding you should use a computed property over watcher.

            – Frank
            Jan 3 at 9:50
















          2












          2








          2







          watcher is probably what you need



          export default {
          // ...
          watch: {
          '$store.getters.getUser'(user) {
          this.name = user.name;
          },
          },
          }





          share|improve this answer













          watcher is probably what you need



          export default {
          // ...
          watch: {
          '$store.getters.getUser'(user) {
          this.name = user.name;
          },
          },
          }






          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Jan 3 at 9:23









          Jacob GohJacob Goh

          7,70311738




          7,70311738








          • 1





            Nice I made it work. Thanks Jacob, in what lifecycle should I call the dispatch? Right now I'm calling it from beforeCreate()

            – Allen Chun
            Jan 3 at 9:38











          • There's no hard rules for this. Normally I do it in created. forum.vuejs.org/t/…

            – Jacob Goh
            Jan 3 at 9:41











          • I think that this use case calls for a computed property instead of a watcher

            – Frank
            Jan 3 at 9:41













          • @AllenChun i think this is what Frank means. Not sure if it is what you want though. vuex.vuejs.org/guide/forms.html#two-way-computed-property

            – Jacob Goh
            Jan 3 at 9:44











          • @JacobGoh Please check my answer. Regardless of whether you want a two-way binding you should use a computed property over watcher.

            – Frank
            Jan 3 at 9:50
















          • 1





            Nice I made it work. Thanks Jacob, in what lifecycle should I call the dispatch? Right now I'm calling it from beforeCreate()

            – Allen Chun
            Jan 3 at 9:38











          • There's no hard rules for this. Normally I do it in created. forum.vuejs.org/t/…

            – Jacob Goh
            Jan 3 at 9:41











          • I think that this use case calls for a computed property instead of a watcher

            – Frank
            Jan 3 at 9:41













          • @AllenChun i think this is what Frank means. Not sure if it is what you want though. vuex.vuejs.org/guide/forms.html#two-way-computed-property

            – Jacob Goh
            Jan 3 at 9:44











          • @JacobGoh Please check my answer. Regardless of whether you want a two-way binding you should use a computed property over watcher.

            – Frank
            Jan 3 at 9:50










          1




          1





          Nice I made it work. Thanks Jacob, in what lifecycle should I call the dispatch? Right now I'm calling it from beforeCreate()

          – Allen Chun
          Jan 3 at 9:38





          Nice I made it work. Thanks Jacob, in what lifecycle should I call the dispatch? Right now I'm calling it from beforeCreate()

          – Allen Chun
          Jan 3 at 9:38













          There's no hard rules for this. Normally I do it in created. forum.vuejs.org/t/…

          – Jacob Goh
          Jan 3 at 9:41





          There's no hard rules for this. Normally I do it in created. forum.vuejs.org/t/…

          – Jacob Goh
          Jan 3 at 9:41













          I think that this use case calls for a computed property instead of a watcher

          – Frank
          Jan 3 at 9:41







          I think that this use case calls for a computed property instead of a watcher

          – Frank
          Jan 3 at 9:41















          @AllenChun i think this is what Frank means. Not sure if it is what you want though. vuex.vuejs.org/guide/forms.html#two-way-computed-property

          – Jacob Goh
          Jan 3 at 9:44





          @AllenChun i think this is what Frank means. Not sure if it is what you want though. vuex.vuejs.org/guide/forms.html#two-way-computed-property

          – Jacob Goh
          Jan 3 at 9:44













          @JacobGoh Please check my answer. Regardless of whether you want a two-way binding you should use a computed property over watcher.

          – Frank
          Jan 3 at 9:50







          @JacobGoh Please check my answer. Regardless of whether you want a two-way binding you should use a computed property over watcher.

          – Frank
          Jan 3 at 9:50















          0














          While Jacob's answer isn't necessarily incorrect, it's better practice to use a computed property instead. You can read about that here



            computed: {
          user(){
          return this.$store.getters.getUser
          }
          }


          Then access name via {{user.name}} or create a name computed property



            computed: {
          name(){
          return this.$store.getters.getUser.name
          }
          }


          Edit: fiddle as example https://jsfiddle.net/uy47cdnw/



          Edit2: Please not that if you want to mutate object via that input field, you should use the link Jacob provided.






          share|improve this answer





















          • 1





            in some cases, you would be very right. I just don't think this is the case here. v-model="name" combine with a computed property without setter is going to be problematic. (god... i feel offended by the unreasonable downvote )

            – Jacob Goh
            Jan 3 at 9:59













          • Initially my approach is using computed property but I need to mutate the object using input field, then I have 10 fields in my form so I find computed property really tedious. There's also an instance I used computed property to set the state and when I refreshed the page the value suddenly gone.

            – Allen Chun
            Jan 3 at 10:02











          • @JacobGoh Alright, i see your point.

            – Frank
            Jan 3 at 10:03
















          0














          While Jacob's answer isn't necessarily incorrect, it's better practice to use a computed property instead. You can read about that here



            computed: {
          user(){
          return this.$store.getters.getUser
          }
          }


          Then access name via {{user.name}} or create a name computed property



            computed: {
          name(){
          return this.$store.getters.getUser.name
          }
          }


          Edit: fiddle as example https://jsfiddle.net/uy47cdnw/



          Edit2: Please not that if you want to mutate object via that input field, you should use the link Jacob provided.






          share|improve this answer





















          • 1





            in some cases, you would be very right. I just don't think this is the case here. v-model="name" combine with a computed property without setter is going to be problematic. (god... i feel offended by the unreasonable downvote )

            – Jacob Goh
            Jan 3 at 9:59













          • Initially my approach is using computed property but I need to mutate the object using input field, then I have 10 fields in my form so I find computed property really tedious. There's also an instance I used computed property to set the state and when I refreshed the page the value suddenly gone.

            – Allen Chun
            Jan 3 at 10:02











          • @JacobGoh Alright, i see your point.

            – Frank
            Jan 3 at 10:03














          0












          0








          0







          While Jacob's answer isn't necessarily incorrect, it's better practice to use a computed property instead. You can read about that here



            computed: {
          user(){
          return this.$store.getters.getUser
          }
          }


          Then access name via {{user.name}} or create a name computed property



            computed: {
          name(){
          return this.$store.getters.getUser.name
          }
          }


          Edit: fiddle as example https://jsfiddle.net/uy47cdnw/



          Edit2: Please not that if you want to mutate object via that input field, you should use the link Jacob provided.






          share|improve this answer















          While Jacob's answer isn't necessarily incorrect, it's better practice to use a computed property instead. You can read about that here



            computed: {
          user(){
          return this.$store.getters.getUser
          }
          }


          Then access name via {{user.name}} or create a name computed property



            computed: {
          name(){
          return this.$store.getters.getUser.name
          }
          }


          Edit: fiddle as example https://jsfiddle.net/uy47cdnw/



          Edit2: Please not that if you want to mutate object via that input field, you should use the link Jacob provided.







          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Jan 3 at 9:56

























          answered Jan 3 at 9:50









          FrankFrank

          6051725




          6051725








          • 1





            in some cases, you would be very right. I just don't think this is the case here. v-model="name" combine with a computed property without setter is going to be problematic. (god... i feel offended by the unreasonable downvote )

            – Jacob Goh
            Jan 3 at 9:59













          • Initially my approach is using computed property but I need to mutate the object using input field, then I have 10 fields in my form so I find computed property really tedious. There's also an instance I used computed property to set the state and when I refreshed the page the value suddenly gone.

            – Allen Chun
            Jan 3 at 10:02











          • @JacobGoh Alright, i see your point.

            – Frank
            Jan 3 at 10:03














          • 1





            in some cases, you would be very right. I just don't think this is the case here. v-model="name" combine with a computed property without setter is going to be problematic. (god... i feel offended by the unreasonable downvote )

            – Jacob Goh
            Jan 3 at 9:59













          • Initially my approach is using computed property but I need to mutate the object using input field, then I have 10 fields in my form so I find computed property really tedious. There's also an instance I used computed property to set the state and when I refreshed the page the value suddenly gone.

            – Allen Chun
            Jan 3 at 10:02











          • @JacobGoh Alright, i see your point.

            – Frank
            Jan 3 at 10:03








          1




          1





          in some cases, you would be very right. I just don't think this is the case here. v-model="name" combine with a computed property without setter is going to be problematic. (god... i feel offended by the unreasonable downvote )

          – Jacob Goh
          Jan 3 at 9:59







          in some cases, you would be very right. I just don't think this is the case here. v-model="name" combine with a computed property without setter is going to be problematic. (god... i feel offended by the unreasonable downvote )

          – Jacob Goh
          Jan 3 at 9:59















          Initially my approach is using computed property but I need to mutate the object using input field, then I have 10 fields in my form so I find computed property really tedious. There's also an instance I used computed property to set the state and when I refreshed the page the value suddenly gone.

          – Allen Chun
          Jan 3 at 10:02





          Initially my approach is using computed property but I need to mutate the object using input field, then I have 10 fields in my form so I find computed property really tedious. There's also an instance I used computed property to set the state and when I refreshed the page the value suddenly gone.

          – Allen Chun
          Jan 3 at 10:02













          @JacobGoh Alright, i see your point.

          – Frank
          Jan 3 at 10:03





          @JacobGoh Alright, i see your point.

          – Frank
          Jan 3 at 10:03


















          draft saved

          draft discarded




















































          Thanks for contributing an answer to Stack Overflow!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid



          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.


          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54019154%2fsetting-value-to-input-field-using-vuex-store-modules%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          'app-layout' is not a known element: how to share Component with different Modules

          android studio warns about leanback feature tag usage required on manifest while using Unity exported app?

          WPF add header to Image with URL pettitions [duplicate]