Search code examples
vue.jsvuexvuex-modules

How to get value of Vuex getter inside of Vue local data object


Hey this seemed to be pretty simple, but I just can't figure out how to get my loggedInUser object to work outside the template. I read through a bunch of other answers and I know I have to do something to store the getter in a local data object.

I have a temporary 'id' object set up because that's what I ultimately want to set to loggedInUser.id in order to attach to my Axios request.

Here's the page I want to make changes on:

<script>

import { mapGetters } from 'vuex'
// import vuex from 'vuex'


export default {
   data: () => ({
      results: "",
      id: "15",
  }),
  computed: {
    ...mapGetters(['loggedInUser'])
  },
  // var id = {{loggedInUser}};
  methods: {

      getData() {
          this.$axios.get('http://127.0.0.1:8000/api/v1/actors/', 
            {params: {user: this.id} }
            )
            .then(response => {this.results = response.data});
           

      }
  }
}
</script>

and here's my index.js for store:

export const getters = {
    isAuthenticated(state) {
        return state.auth.loggedIn
    },
    loggedInUser(state) {
        return state.auth.user
    }
}

Solution

  • The mapGetters helper simply maps store getters to local computed properties

    This:

    computed: {
      ...mapGetters(['loggedInUser'])
    },
    

    Is equivalent to this:

    computed: {
      loggedInUser() {
        return this.$store.getters.loggedInUser
      },
    },
    

    Replace this.id with this.loggedInUser.id in your axios request, and get rid of the temporary id data property.

     getData() {
       this.$axios.get('http://127.0.0.1:8000/api/v1/actors/', {
           params: {
             user: this.loggedInUser.id
           }
         })
         .then(response => {
           this.results = response.data
         });
     }
    

    We are assuming getData only gets called when the user is authenticated. If that's not the case, have in mind this.loggedInUser may be null or undefined and accessing this.loggedInUser.id will throw an error.