Moses Anumadu I'm a software developer with an interest in writing technical articles and tutorials. I have over four years of coding experience with various technologies. I love to share knowledge in the form of writing.

A complete guide to mapping in Vuex

3 min read 893

A Complete Guide To Mapping In Vuex

Vuex is a double-edged sword. If used properly, it can make your life a lot easier when working with Vue. It can also make a mess of your codebase if you’re not careful.

There are four main concepts you shouldunderstand before you use Vuex: state, getters, mutations, and actions. A simple Vuex state manipulates data within these concepts in the store. Mapping in Vuex provides a nice, clean way of retrieving data from them.

In this tutorial, we’ll demonstrate how to map data from the Vuex store. If you’re a Vue developer who’s familiar with the basics of Vuex, these best practices will help you write cleaner and more maintainable code.

This tutorial is targeted an average Vue.js developer who knows the basics of Vue.js and Vuex. who is on a quest to write cleaner and maintainable code using best practices.

What is mapping in Vuex?

Mapping in Vuex enables you to bind any of the state’s properties (getters, mutations, actions, state) to a computed property in a component and use data directly from the state.

Below is an example of a simple Vuex store with test data in state.

import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

const store = new Vuex.Store({
  state: {
    data: "test data"
  }
  }
})

If you want to access the value of data from the State, you can do the following in your Vue.js component.

computed: {
        getData(){
          return this.$store.state.data
        }
    }

The above code works but quickly gets ugly as data in the state starts to grow.

For example:

import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

const store = new Vuex.Store({
  state: {
    user: {
        id:1,
        age:23,
        role:user
        data:{
          name:"user name",
          address:"user address"
        }
    },
    services: {},
    medical_requests: {},
    appointments: {},
    }
  }
})

To get the username from the user object in state:

We made a custom demo for .
No really. Click here to check it out.

computed: {
        getUserName(){
          return this.$store.state.user.data.name
        }
    }

This will get the job done, but there is a better way.

Mapping the state

To map the state to a computed property in the Vue.js component, run the following.

import { mapGetters } from 'vuex';

export default{
    computed: {
        ...mapState([
            'user',
        ])
    }
}

You now have access to the entire user object within the component.

You can do even more, such as add objects from the state to the mapState method.

import { mapGetters } from 'vuex';

export default{
    computed: {
        ...mapState([
            'user',
            'services'
        ])
    }
}

As you can see, this is a lot cleaner. You can easily access the username with:

{{user.data.name}}

The same goes for the services object and many other values mapped.

Did you notice how we passed in an array to the mapState()? If you need to give the value a different name, you can pass in an object instead.

import { mapGetters } from 'vuex';

export default{
    computed: {
        ...mapState({
            userDetails:'user',
            userServices:'services'
        })
    }
}

Now you can reference the user by simply calling userDetails.

When to map the entire state

As a rule of thumb, you should map only when you have lots of data in the state and need them all in the component.

In the example above, it would not make much sense to map the entire user object if all we need from it is just one value — the username, for example.

When you map, the entire object is loaded into memory. You don’t want to keep loading data to memory that you don’t because it would be redundant and lead to performance implications in the long run.

Mapping getters

I’ll assume you know the basics of getters in Vuex and proceed to mapping getters. Check out the Vuex documentation for more information.

Mapping getters is similar in syntax to the mapState function.

import { mapGetters } from 'vuex'

export default {
  computed: {
    ...mapGetters([
      'firstCount',
      'anotherGetter',
    ])
  }
}

Similar to the mapped state, you can pass in an object to the mapGetters function if you intend to use a different name.

import { mapGetters } from 'vuex'

export default {
  computed: {
    ...mapGetters([
      first:'firstCount',
      another:'anotherGetter',
    ])
  }
}

Mapping mutations

Unlike mapState and mapGetters, which are mapped in the computed property of Vue to make data on state reactive with data in the component, Mutations are mapped in the method.

You can commit your mutation using the following syntax in Vue when you map your mutations.

this.$store.commit('mutationName`)

For example:

import { mapMutations } from 'vuex'

export default {
  methods: {
    ...mapMutations([
      'search', // map `this.increment()` to `this.$store.commit('search')`

      // `mapMutations` also supports payloads:
      'searchBy' // map `this.incrementBy(amount)` to `this.$store.commit('searchBy', amount)`
    ]),
    ...mapMutations({
      find: 'search' // map `this.add()` to `this.$store.commit('search')`
    })
  }
}

Mapping actions

Mapping actions is a lot like mapping mutations because it is also done in the method. Using a mapper binds the this.$store.dispatch('actionName') to the name in the array of the mapper or the key of the object.

import { mapActions } from 'vuex'

export default {
  // ...
  methods: {
    ...mapActions([
      'increment', // map `this.increment()` to `this.$store.dispatch('increment')`

      // `mapActions` also supports payloads:
      'incrementBy' // map `this.incrementBy(amount)` to `this.$store.dispatch('incrementBy', amount)`
    ]),
    ...mapActions({
      add: 'increment' // map `this.add()` to `this.$store.dispatch('increment')`
    })
  }
}

Conclusion

By now, you should:

  • Have a firm understanding of how mapping in Vuex works and why you should use it
  • Be able to map all the components in the Vuex store (state, getters, mutations, actions)
  • Know when to map the store and when not to

These best practices will help you immensely if you decide to use Vuex in your next project.

Experience your Vue apps exactly how a user does

Debugging Vue.js applications can be difficult, especially when there are dozens, if not hundreds of mutations during a user session. If you’re interested in monitoring and tracking Vue mutations for all of your users in production, try LogRocket. https://logrocket.com/signup/

LogRocket is like a DVR for web apps, recording literally everything that happens in your Vue apps including network requests, JavaScript errors, performance problems, and much more. Instead of guessing why problems happen, you can aggregate and report on what state your application was in when an issue occurred.

The LogRocket Vuex plugin logs Vuex mutations to the LogRocket console, giving you context around what led to an error, and what state the application was in when an issue occurred.

Modernize how you debug your Vue apps - .

Moses Anumadu I'm a software developer with an interest in writing technical articles and tutorials. I have over four years of coding experience with various technologies. I love to share knowledge in the form of writing.

One Reply to “A complete guide to mapping in Vuex”

Leave a Reply