2018-03-22 06:50:52 -04:00
# Vuex
2018-05-04 09:58:47 -04:00
To manage the state of an application you should use [Vuex][vuex-docs].
2018-03-22 06:25:03 -04:00
_Note:_ All of the below is explained in more detail in the official [Vuex documentation][vuex-docs].
2018-03-22 06:50:52 -04:00
## Separation of concerns
2018-03-22 06:25:03 -04:00
Vuex is composed of State, Getters, Mutations, Actions and Modules.
When a user clicks on an action, we need to `dispatch` it. This action will `commit` a mutation that will change the state.
_Note:_ The action itself will not update the state, only a mutation should update the state.
2018-03-22 06:50:52 -04:00
## File structure
When using Vuex at GitLab, separate this concerns into different files to improve readability:
2018-03-22 06:25:03 -04:00
```
└── store
├── index.js # where we assemble modules and export the store
├── actions.js # actions
├── mutations.js # mutations
├── getters.js # getters
2018-04-04 15:15:04 -04:00
├── state.js # state
2018-03-22 06:25:03 -04:00
└── mutation_types.js # mutation types
```
2018-03-22 06:50:52 -04:00
The following example shows an application that lists and adds users to the state.
2018-05-07 05:09:49 -04:00
(For a more complex example implementation take a look at the security applications store in [here ](https://gitlab.com/gitlab-org/gitlab-ee/tree/master/ee/app/assets/javascripts/vue_shared/security_reports/store ))
2018-03-22 06:25:03 -04:00
2018-03-22 06:50:52 -04:00
### `index.js`
2018-03-22 06:25:03 -04:00
This is the entry point for our store. You can use the following as a guide:
```javascript
import Vue from 'vue';
import Vuex from 'vuex';
import * as actions from './actions';
import * as getters from './getters';
import mutations from './mutations';
2018-03-22 06:50:52 -04:00
import state from './state';
2018-03-22 06:25:03 -04:00
Vue.use(Vuex);
2018-05-18 04:39:42 -04:00
export const createStore = () => new Vuex.Store({
2018-03-22 06:25:03 -04:00
actions,
getters,
mutations,
2018-03-22 06:50:52 -04:00
state,
2018-03-22 06:25:03 -04:00
});
2018-05-18 04:39:42 -04:00
export default createStore();
2018-03-22 06:25:03 -04:00
```
2018-03-22 06:50:52 -04:00
### `state.js`
The first thing you should do before writing any code is to design the state.
Often we need to provide data from haml to our Vue application. Let's store it in the state for better access.
```javascript
2019-03-10 15:24:04 -04:00
export default () => ({
2018-03-22 06:50:52 -04:00
endpoint: null,
isLoading: false,
error: null,
isAddingUser: false,
errorAddingUser: false,
users: [],
2019-03-10 15:24:04 -04:00
});
2018-03-22 06:50:52 -04:00
```
#### Access `state` properties
You can use `mapState` to access state properties in the components.
### `actions.js`
2018-05-11 08:39:32 -04:00
An action is a payload of information to send data from our application to our store.
2018-03-22 06:25:03 -04:00
An action is usually composed by a `type` and a `payload` and they describe what happened.
2018-05-14 07:41:50 -04:00
Enforcing that every change is described as an action lets us have a clear understanding of what is going on in the app.
2018-03-22 06:25:03 -04:00
2018-04-04 15:15:04 -04:00
In this file, we will write the actions that will call the respective mutations:
2018-03-22 06:25:03 -04:00
```javascript
import * as types from './mutation_types';
2018-06-20 15:55:59 -04:00
import axios from '~/lib/utils/axios_utils';
2018-04-04 15:15:04 -04:00
import createFlash from '~/flash';
2018-03-22 06:25:03 -04:00
export const requestUsers = ({ commit }) => commit(types.REQUEST_USERS);
export const receiveUsersSuccess = ({ commit }, data) => commit(types.RECEIVE_USERS_SUCCESS, data);
2019-04-08 11:16:21 -04:00
export const receiveUsersError = ({ commit }, error) => commit(types.RECEIVE_USERS_ERROR, error);
2018-03-22 06:25:03 -04:00
export const fetchUsers = ({ state, dispatch }) => {
dispatch('requestUsers');
2018-05-14 07:31:14 -04:00
axios.get(state.endpoint)
2018-03-22 06:25:03 -04:00
.then(({ data }) => dispatch('receiveUsersSuccess', data))
2018-04-04 15:15:04 -04:00
.catch((error) => {
dispatch('receiveUsersError', error)
createFlash('There was an error')
});
2018-03-22 06:25:03 -04:00
}
export const requestAddUser = ({ commit }) => commit(types.REQUEST_ADD_USER);
export const receiveAddUserSuccess = ({ commit }, data) => commit(types.RECEIVE_ADD_USER_SUCCESS, data);
export const receiveAddUserError = ({ commit }, error) => commit(types.REQUEST_ADD_USER_ERROR, error);
export const addUser = ({ state, dispatch }, user) => {
dispatch('requestAddUser');
2018-05-14 07:31:14 -04:00
axios.post(state.endpoint, user)
2018-03-22 06:25:03 -04:00
.then(({ data }) => dispatch('receiveAddUserSuccess', data))
.catch((error) => dispatch('receiveAddUserError', error));
}
```
2018-03-22 06:50:52 -04:00
#### Actions Pattern: `request` and `receive` namespaces
2018-03-22 06:25:03 -04:00
When a request is made we often want to show a loading state to the user.
Instead of creating an action to toggle the loading state and dispatch it in the component,
create:
2018-11-12 19:39:21 -05:00
2018-04-04 15:15:04 -04:00
1. An action `requestSomething` , to toggle the loading state
1. An action `receiveSomethingSuccess` , to handle the success callback
1. An action `receiveSomethingError` , to handle the error callback
2018-05-04 09:58:47 -04:00
1. An action `fetchSomething` to make the request.
1. In case your application does more than a `GET` request you can use these as examples:
2019-01-18 10:32:13 -05:00
- `POST` : `createSomething`
- `PUT` : `updateSomething`
2018-11-12 19:39:21 -05:00
- `DELETE` : `deleteSomething`
2018-03-22 06:25:03 -04:00
2018-04-06 04:38:19 -04:00
The component MUST only dispatch the `fetchNamespace` action. Actions namespaced with `request` or `receive` should not be called from the component
2018-03-22 06:25:03 -04:00
The `fetch` action will be responsible to dispatch `requestNamespace` , `receiveNamespaceSuccess` and `receiveNamespaceError`
2018-04-04 15:15:04 -04:00
By following this pattern we guarantee:
2018-11-12 19:39:21 -05:00
2018-05-14 07:41:50 -04:00
1. All applications follow the same pattern, making it easier for anyone to maintain the code
2018-03-22 06:25:03 -04:00
1. All data in the application follows the same lifecycle pattern
1. Actions are contained and human friendly
1. Unit tests are easier
1. Actions are simple and straightforward
2018-03-22 06:50:52 -04:00
#### Dispatching actions
2018-03-22 06:25:03 -04:00
To dispatch an action from a component, use the `mapActions` helper:
2018-12-11 09:49:49 -05:00
2018-03-22 06:25:03 -04:00
```javascript
import { mapActions } from 'vuex';
{
methods: {
...mapActions([
'addUser',
]),
onClickUser(user) {
this.addUser(user);
},
},
};
```
2018-05-08 10:51:29 -04:00
### `mutations.js`
2018-03-22 06:25:03 -04:00
The mutations specify how the application state changes in response to actions sent to the store.
2018-04-04 15:15:04 -04:00
The only way to change state in a Vuex store should be by committing a mutation.
2018-03-22 06:25:03 -04:00
2018-04-04 15:15:04 -04:00
**It's a good idea to think of the state before writing any code.**
2018-03-22 06:25:03 -04:00
2018-04-04 15:15:04 -04:00
Remember that actions only describe that something happened, they don't describe how the application state changes.
2018-03-22 06:25:03 -04:00
**Never commit a mutation directly from a component**
```javascript
import * as types from './mutation_types';
export default {
2018-03-22 06:50:52 -04:00
[types.REQUEST_USERS ](state ) {
2018-04-04 15:15:04 -04:00
state.isLoading = true;
2018-03-22 06:50:52 -04:00
},
[types.RECEIVE_USERS_SUCCESS ](state, data ) {
// Do any needed data transformation to the received payload here
2018-04-04 15:15:04 -04:00
state.users = data;
state.isLoading = false;
2018-03-22 06:50:52 -04:00
},
2019-04-08 11:16:21 -04:00
[types.RECEIVE_USERS_ERROR ](state, error ) {
2018-04-04 15:15:04 -04:00
state.isLoading = false;
2018-03-22 06:50:52 -04:00
},
[types.REQUEST_ADD_USER ](state, user ) {
2018-05-14 07:50:19 -04:00
state.isAddingUser = true;
2018-03-22 06:50:52 -04:00
},
[types.RECEIVE_ADD_USER_SUCCESS ](state, user ) {
2018-04-04 15:15:04 -04:00
state.isAddingUser = false;
2018-03-22 06:25:03 -04:00
state.users.push(user);
},
2018-03-22 06:50:52 -04:00
[types.REQUEST_ADD_USER_ERROR ](state, error ) {
2018-04-04 15:15:04 -04:00
state.isAddingUser = true;
2018-05-14 07:50:19 -04:00
state.errorAddingUser = error;
2018-03-22 06:50:52 -04:00
},
2018-03-22 06:25:03 -04:00
};
```
2018-05-08 10:51:29 -04:00
### `getters.js`
2018-03-22 06:25:03 -04:00
Sometimes we may need to get derived state based on store state, like filtering for a specific prop.
2018-05-07 05:09:49 -04:00
Using a getter will also cache the result based on dependencies due to [how computed props work ](https://vuejs.org/v2/guide/computed.html#Computed-Caching-vs-Methods )
2018-03-22 06:25:03 -04:00
This can be done through the `getters` :
```javascript
// get all the users with pets
2018-04-04 15:15:04 -04:00
export const getUsersWithPets = (state, getters) => {
2018-03-22 06:25:03 -04:00
return state.users.filter(user => user.pet !== undefined);
};
```
To access a getter from a component, use the `mapGetters` helper:
2018-12-11 09:49:49 -05:00
2018-03-22 06:25:03 -04:00
```javascript
import { mapGetters } from 'vuex';
{
computed: {
...mapGetters([
'getUsersWithPets',
]),
},
};
```
2018-06-20 15:55:59 -04:00
### `mutation_types.js`
2018-03-22 06:25:03 -04:00
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
export const ADD_USER = 'ADD_USER';
```
### How to include the store in your application
The store should be included in the main component of your application:
2018-12-11 09:49:49 -05:00
2018-03-22 06:25:03 -04:00
```javascript
// app.vue
import store from 'store'; // it will include the index.js file
export default {
name: 'application',
store,
...
};
```
2018-03-22 06:50:52 -04:00
### Communicating with the Store
```javascript
< script >
import { mapActions, mapState, mapGetters } from 'vuex';
import store from './store';
export default {
store,
computed: {
...mapGetters([
'getUsersWithPets'
]),
...mapState([
'isLoading',
'users',
'error',
]),
},
methods: {
...mapActions([
'fetchUsers',
'addUser',
]),
onClickAddUser(data) {
this.addUser(data);
}
},
created() {
this.fetchUsers()
}
}
< / script >
< template >
< ul >
< li v-if = "isLoading" >
Loading...
< / li >
< li v-else-if = "error" >
{{ error }}
< / li >
2018-04-04 15:15:04 -04:00
< template v-else >
< li
v-for="user in users"
:key="user.id"
>
{{ user }}
< / li >
< / template >
2018-03-22 06:50:52 -04:00
< / ul >
< / template >
```
2018-03-22 06:25:03 -04:00
### Vuex Gotchas
2018-09-06 12:52:18 -04:00
1. Do not call a mutation directly. Always use an action to commit a mutation. Doing so will keep consistency throughout the application. From Vuex docs:
2018-03-22 06:25:03 -04:00
2018-09-06 12:52:18 -04:00
> 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
2018-11-12 19:39:21 -05:00
2018-09-06 12:52:18 -04:00
// bad
created() {
this.$store.commit('mutation');
}
2018-11-12 19:39:21 -05:00
2018-09-06 12:52:18 -04:00
// good
created() {
this.$store.dispatch('action');
}
```
2018-03-22 06:25:03 -04:00
1. 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:
```javascript
//component_spec.js
import Vue from 'vue';
2018-05-18 04:39:42 -04:00
import { createStore } from './store';
2018-03-22 06:25:03 -04:00
import component from './component.vue'
describe('component', () => {
2018-05-18 04:39:42 -04:00
let store;
2018-03-22 06:25:03 -04:00
let vm;
let Component;
beforeEach(() => {
Component = Vue.extend(issueActions);
});
afterEach(() => {
vm.$destroy();
});
it('should show a user', () => {
const user = {
name: 'Foo',
age: '30',
};
2018-09-06 12:52:18 -04:00
2018-05-18 04:39:42 -04:00
store = createStore();
2018-03-22 06:25:03 -04:00
// populate the store
2018-05-14 07:41:50 -04:00
store.dispatch('addUser', user);
2018-03-22 06:25:03 -04:00
vm = new Component({
store,
propsData: props,
}).$mount();
});
});
```
2018-05-08 10:55:49 -04:00
#### Testing Vuex actions and getters
2018-05-08 13:13:22 -04:00
Because we're currently using [`babel-plugin-rewire` ](https://github.com/speedskater/babel-plugin-rewire ), you may encounter the following error when testing your Vuex actions and getters:
2018-05-08 10:55:49 -04:00
`[vuex] actions should be function or object with "handler" function`
2018-05-14 07:16:24 -04:00
To prevent this error from happening, you need to export an empty function as `default` :
2018-12-11 09:49:49 -05:00
```javascript
2018-05-08 10:56:43 -04:00
// getters.js or actions.js
2018-05-08 10:55:49 -04:00
// prevent babel-plugin-rewire from generating an invalid default during karma tests
export default () => {};
```
2018-03-22 06:25:03 -04:00
[vuex-docs]: https://vuex.vuejs.org
[vuex-structure]: https://vuex.vuejs.org/en/structure.html
[vuex-mutations]: https://vuex.vuejs.org/en/mutations.html
2018-04-04 15:15:04 -04:00
[vuex-testing]: https://vuex.vuejs.org/en/testing.html