When we need to query the `gl` object for data that won't change during the application's lyfecyle, we should do it in the same place where we query the DOM.
By following this practice, we can avoid the need to mock the `gl` object, which will make tests easier.
It should be done while initializing our Vue instance, and the data should be provided as `props` to the main component:
To access a getter from a component, use the `mapGetters` helper:
```javascript
import{mapGetters}from'vuex';
{
computed:{
...mapGetters([
'getUsersWithPets',
]),
},
};
```
#### `mutations.js`
The only way to actually change state in a Vuex store is by committing a mutation.
```javascript
import*astypesfrom'./mutation-types'
exportdefault{
[types.ADD_USER](state,user){
state.users.push(user);
},
};
```
#### `mutations_types.js`
From [vuex mutations docs][vuex-mutations]:
> It is a commonly seen pattern to use constants for mutation types in various Flux implementations. This allows the code to take advantage of tooling like linters, and putting all constants in a single file allows your collaborators to get an at-a-glance view of what mutations are possible in the entire application.
```javascript
exportconstADD_USER='ADD_USER';
```
### How to include the store in your application
The store should be included in the main component of your application:
```javascript
// app.vue
importstorefrom'store';// it will include the index.js file
exportdefault{
name:'application',
store,
...
};
```
### Vuex Gotchas
1. Avoid calling a mutation directly. Always use an action to commit a mutation. Doing so will keep consistency through out the application. From Vuex docs:
> why don't we just call store.commit('action') directly? Well, remember that mutations must be synchronous? Actions aren't. We can perform asynchronous operations inside an action.
```javascript
// component.vue
// bad
created(){
this.$store.commit('mutation');
}
// good
created(){
this.$store.dispatch('action');
}
```
1. When possible, use mutation types instead of hardcoding strings. It will be less error prone.
1. The State will be accessible in all components descending from the use where the store is instantiated.
### Testing Vuex
#### Testing Vuex concerns
Refer to [vuex docs][vuex-testing] regarding testing Actions, Getters and Mutations.
#### Testing components that need a store
Smaller components might use `store` properties to access the data.
In order to write unit tests for those components, we need to include the store and provide the correct state: