debian-mirror-gitlab/doc/development/fe_guide/vuex.md

623 lines
17 KiB
Markdown
Raw Normal View History

2021-01-29 00:20:46 +05:30
---
stage: none
group: unassigned
2022-11-25 23:54:43 +05:30
info: To determine the technical writer assigned to the Stage/Group associated with this page, see https://about.gitlab.com/handbook/product/ux/technical-writing/#assignments
2021-01-29 00:20:46 +05:30
---
2018-10-15 14:42:47 +05:30
# Vuex
2019-10-12 21:52:04 +05:30
2021-02-22 17:27:13 +05:30
When there's a clear benefit to separating state management from components (for example, due to state complexity) we recommend using [Vuex](https://vuex.vuejs.org) over any other Flux pattern. Otherwise, feel free to manage state in the components.
2020-04-08 14:13:33 +05:30
Vuex should be strongly considered when:
2021-02-22 17:27:13 +05:30
- You expect multiple parts of the application to react to state changes.
- There's a need to share data between multiple components.
- There are complex interactions with Backend, for example, multiple API calls.
- The app involves interacting with backend via both traditional REST API and GraphQL (especially when moving the REST API over to GraphQL is a pending backend task).
2018-10-15 14:42:47 +05:30
2021-01-29 00:20:46 +05:30
The information included in this page is explained in more detail in the
official [Vuex documentation](https://vuex.vuejs.org).
2018-10-15 14:42:47 +05:30
## Separation of concerns
2019-10-12 21:52:04 +05:30
2020-04-08 14:13:33 +05:30
Vuex is composed of State, Getters, Mutations, Actions, and Modules.
2018-10-15 14:42:47 +05:30
2023-01-13 00:05:48 +05:30
When a user selects an action, we need to `dispatch` it. This action `commits` a mutation that changes the state. The action itself does not update the state; only a mutation should update the state.
2018-10-15 14:42:47 +05:30
## File structure
2019-10-12 21:52:04 +05:30
2019-12-04 20:38:33 +05:30
When using Vuex at GitLab, separate these concerns into different files to improve readability:
2018-10-15 14:42:47 +05:30
2020-04-22 19:07:51 +05:30
```plaintext
2018-10-15 14:42:47 +05:30
└── store
├── index.js # where we assemble modules and export the store
├── actions.js # actions
├── mutations.js # mutations
├── getters.js # getters
├── state.js # state
└── mutation_types.js # mutation types
```
2019-10-12 21:52:04 +05:30
2021-01-03 14:25:43 +05:30
The following example shows an application that lists and adds users to the
state. (For a more complex example implementation, review the security
2021-09-04 01:27:46 +05:30
applications stored in this [repository](https://gitlab.com/gitlab-org/gitlab/-/tree/master/ee/app/assets/javascripts/vue_shared/security_reports/store)).
2018-10-15 14:42:47 +05:30
### `index.js`
2019-10-12 21:52:04 +05:30
2018-10-15 14:42:47 +05:30
This is the entry point for our store. You can use the following as a guide:
```javascript
import Vuex from 'vuex';
import * as actions from './actions';
import * as getters from './getters';
import mutations from './mutations';
import state from './state';
2020-10-24 23:57:45 +05:30
export const createStore = () =>
new Vuex.Store({
actions,
getters,
mutations,
state,
});
2018-10-15 14:42:47 +05:30
```
### `state.js`
2019-10-12 21:52:04 +05:30
2018-10-15 14:42:47 +05:30
The first thing you should do before writing any code is to design the state.
2021-01-29 00:20:46 +05:30
Often we need to provide data from HAML to our Vue application. Let's store it in the state for better access.
2018-10-15 14:42:47 +05:30
```javascript
2019-07-07 11:18:12 +05:30
export default () => ({
2018-10-15 14:42:47 +05:30
endpoint: null,
isLoading: false,
error: null,
isAddingUser: false,
errorAddingUser: false,
users: [],
2019-07-07 11:18:12 +05:30
});
2018-10-15 14:42:47 +05:30
```
#### Access `state` properties
2019-10-12 21:52:04 +05:30
2018-10-15 14:42:47 +05:30
You can use `mapState` to access state properties in the components.
### `actions.js`
2019-10-12 21:52:04 +05:30
2018-11-08 19:23:39 +05:30
An action is a payload of information to send data from our application to our store.
2018-10-15 14:42:47 +05:30
2020-05-24 23:13:21 +05:30
An action is usually composed by a `type` and a `payload` and they describe what happened. Unlike [mutations](#mutationsjs), actions can contain asynchronous operations - that's why we always need to handle asynchronous logic in actions.
2018-10-15 14:42:47 +05:30
2021-02-22 17:27:13 +05:30
In this file, we write the actions that call mutations for handling a list of users:
2018-10-15 14:42:47 +05:30
```javascript
import * as types from './mutation_types';
2018-11-08 19:23:39 +05:30
import axios from '~/lib/utils/axios_utils';
2018-10-15 14:42:47 +05:30
import createFlash from '~/flash';
export const fetchUsers = ({ state, dispatch }) => {
2020-05-24 23:13:21 +05:30
commit(types.REQUEST_USERS);
2018-10-15 14:42:47 +05:30
2018-11-08 19:23:39 +05:30
axios.get(state.endpoint)
2020-05-24 23:13:21 +05:30
.then(({ data }) => commit(types.RECEIVE_USERS_SUCCESS, data))
2018-10-15 14:42:47 +05:30
.catch((error) => {
2020-05-24 23:13:21 +05:30
commit(types.RECEIVE_USERS_ERROR, error)
2021-09-30 23:02:18 +05:30
createFlash({ message: 'There was an error' })
2018-10-15 14:42:47 +05:30
});
}
export const addUser = ({ state, dispatch }, user) => {
2020-05-24 23:13:21 +05:30
commit(types.REQUEST_ADD_USER);
2018-10-15 14:42:47 +05:30
2018-11-08 19:23:39 +05:30
axios.post(state.endpoint, user)
2020-05-24 23:13:21 +05:30
.then(({ data }) => commit(types.RECEIVE_ADD_USER_SUCCESS, data))
.catch((error) => commit(types.REQUEST_ADD_USER_ERROR, error));
2018-10-15 14:42:47 +05:30
}
```
#### Dispatching actions
2019-10-12 21:52:04 +05:30
2018-10-15 14:42:47 +05:30
To dispatch an action from a component, use the `mapActions` helper:
2019-02-15 15:39:39 +05:30
2018-10-15 14:42:47 +05:30
```javascript
import { mapActions } from 'vuex';
{
methods: {
...mapActions([
'addUser',
]),
onClickUser(user) {
this.addUser(user);
},
},
};
```
2018-11-08 19:23:39 +05:30
### `mutations.js`
2019-10-12 21:52:04 +05:30
2018-10-15 14:42:47 +05:30
The mutations specify how the application state changes in response to actions sent to the store.
2020-10-24 23:57:45 +05:30
The only way to change state in a Vuex store is by committing a mutation.
2018-10-15 14:42:47 +05:30
2020-10-24 23:57:45 +05:30
Most mutations are committed from an action using `commit`. If you don't have any
asynchronous operations, you can call mutations from a component using the `mapMutations` helper.
2018-10-15 14:42:47 +05:30
2021-03-11 19:13:27 +05:30
See the Vuex documentation for examples of [committing mutations from components](https://vuex.vuejs.org/guide/mutations.html#committing-mutations-in-components).
2018-10-15 14:42:47 +05:30
2020-05-24 23:13:21 +05:30
#### Naming Pattern: `REQUEST` and `RECEIVE` namespaces
When a request is made we often want to show a loading state to the user.
Instead of creating an mutation to toggle the loading state, we should:
1. A mutation with type `REQUEST_SOMETHING`, to toggle the loading state
1. A mutation with type `RECEIVE_SOMETHING_SUCCESS`, to handle the success callback
1. A mutation with type `RECEIVE_SOMETHING_ERROR`, to handle the error callback
1. An action `fetchSomething` to make the request and commit mutations on mentioned cases
1. In case your application does more than a `GET` request you can use these as examples:
- `POST`: `createSomething`
- `PUT`: `updateSomething`
- `DELETE`: `deleteSomething`
2021-02-22 17:27:13 +05:30
As a result, we can dispatch the `fetchNamespace` action from the component and it is responsible to commit `REQUEST_NAMESPACE`, `RECEIVE_NAMESPACE_SUCCESS` and `RECEIVE_NAMESPACE_ERROR` mutations.
2020-05-24 23:13:21 +05:30
2022-08-27 11:52:29 +05:30
> Previously, we were dispatching actions from the `fetchNamespace` action instead of committing mutation, so don't be confused if you find a different pattern in the older parts of the codebase. However, we encourage leveraging a new pattern whenever you write new Vuex stores.
2020-05-24 23:13:21 +05:30
By following this pattern we guarantee:
2021-02-22 17:27:13 +05:30
1. All applications follow the same pattern, making it easier for anyone to maintain the code.
1. All data in the application follows the same lifecycle pattern.
1. Unit tests are easier.
2020-05-24 23:13:21 +05:30
2020-07-28 23:09:34 +05:30
#### Updating complex state
Sometimes, especially when the state is complex, is really hard to traverse the state to precisely update what the mutation needs to update.
Ideally a `vuex` state should be as normalized/decoupled as possible but this is not always the case.
It's important to remember that the code is much easier to read and maintain when the `portion of the mutated state` is selected and mutated in the mutation itself.
Given this state:
```javascript
export default () => ({
items: [
{
id: 1,
name: 'my_issue',
closed: false,
},
{
id: 2,
name: 'another_issue',
closed: false,
}
]
});
```
It may be tempting to write a mutation like so:
```javascript
// Bad
export default {
[types.MARK_AS_CLOSED](state, item) {
Object.assign(item, {closed: true})
}
}
```
While this approach works it has several dependencies:
- Correct selection of `item` in the component/action.
- The `item` property is already declared in the `closed` state.
- A new `confidential` property would not be reactive.
2021-02-22 17:27:13 +05:30
- Noting that `item` is referenced by `items`.
2020-07-28 23:09:34 +05:30
A mutation written like this is harder to maintain and more error prone. We should rather write a mutation like this:
```javascript
// Good
export default {
[types.MARK_AS_CLOSED](state, itemId) {
2020-11-24 15:15:51 +05:30
const item = state.items.find(x => x.id === itemId);
2020-07-28 23:09:34 +05:30
2020-11-24 15:15:51 +05:30
if (!item) {
return;
}
Vue.set(item, 'closed', true);
},
};
2020-07-28 23:09:34 +05:30
```
This approach is better because:
- It selects and updates the state in the mutation, which is more maintainable.
- It has no external dependencies, if the correct `itemId` is passed the state is correctly updated.
- It does not have reactivity caveats, as we generate a new `item` to avoid coupling to the initial state.
A mutation written like this is easier to maintain. In addition, we avoid errors due to the limitation of the reactivity system.
2018-11-08 19:23:39 +05:30
### `getters.js`
2019-10-12 21:52:04 +05:30
2018-10-15 14:42:47 +05:30
Sometimes we may need to get derived state based on store state, like filtering for a specific prop.
2022-10-11 01:57:18 +05:30
Using a getter also caches the result based on dependencies due to [how computed props work](https://v2.vuejs.org/v2/guide/computed.html#Computed-Caching-vs-Methods)
2018-10-15 14:42:47 +05:30
This can be done through the `getters`:
```javascript
// get all the users with pets
export const getUsersWithPets = (state, getters) => {
return state.users.filter(user => user.pet !== undefined);
};
```
To access a getter from a component, use the `mapGetters` helper:
2019-02-15 15:39:39 +05:30
2018-10-15 14:42:47 +05:30
```javascript
import { mapGetters } from 'vuex';
{
computed: {
...mapGetters([
'getUsersWithPets',
]),
},
};
```
2018-11-08 19:23:39 +05:30
### `mutation_types.js`
2019-10-12 21:52:04 +05:30
2021-03-11 19:13:27 +05:30
From [Vuex mutations documentation](https://vuex.vuejs.org/guide/mutations.html):
2021-02-22 17:27:13 +05:30
> 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.
2018-10-15 14:42:47 +05:30
```javascript
export const ADD_USER = 'ADD_USER';
```
2020-04-22 19:07:51 +05:30
### Initializing a store's state
It's common for a Vuex store to need some initial state before its `action`s can
be used. Often this includes data like API endpoints, documentation URLs, or
IDs.
2019-10-12 21:52:04 +05:30
2020-04-22 19:07:51 +05:30
To set this initial state, pass it as a parameter to your store's creation
function when mounting your Vue component:
2019-02-15 15:39:39 +05:30
2018-10-15 14:42:47 +05:30
```javascript
2020-04-22 19:07:51 +05:30
// in the Vue app's initialization script (e.g. mount_show.js)
2018-10-15 14:42:47 +05:30
2020-04-22 19:07:51 +05:30
import Vue from 'vue';
2020-10-24 23:57:45 +05:30
import Vuex from 'vuex';
import { createStore } from './stores';
2020-04-22 19:07:51 +05:30
import AwesomeVueApp from './components/awesome_vue_app.vue'
2020-10-24 23:57:45 +05:30
Vue.use(Vuex);
2020-04-22 19:07:51 +05:30
export default () => {
const el = document.getElementById('js-awesome-vue-app');
return new Vue({
el,
store: createStore(el.dataset),
render: h => h(AwesomeVueApp)
});
};
```
The store function, in turn, can pass this data along to the state's creation
function:
```javascript
// in store/index.js
import * as actions from './actions';
import mutations from './mutations';
import createState from './state';
export default initialState => ({
actions,
mutations,
state: createState(initialState),
});
2018-10-15 14:42:47 +05:30
```
2020-04-22 19:07:51 +05:30
And the state function can accept this initial data as a parameter and bake it
into the `state` object it returns:
```javascript
// in store/state.js
export default ({
projectId,
documentationPath,
anOptionalProperty = true
}) => ({
projectId,
documentationPath,
anOptionalProperty,
// other state properties here
});
```
#### Why not just ...spread the initial state?
2021-02-22 17:27:13 +05:30
The astute reader sees an opportunity to cut out a few lines of code from
2020-04-22 19:07:51 +05:30
the example above:
```javascript
// Don't do this!
export default initialState => ({
...initialState,
// other state properties here
});
```
2021-02-22 17:27:13 +05:30
We made the conscious decision to avoid this pattern to improve the ability to
discover and search our frontend codebase. The same applies
2022-10-11 01:57:18 +05:30
when [providing data to a Vue app](vue.md#providing-data-from-haml-to-javascript). The reasoning for this is described in
2022-08-27 11:52:29 +05:30
[this discussion](https://gitlab.com/gitlab-org/frontend/rfcs/-/issues/56#note_302514865):
2020-04-22 19:07:51 +05:30
> Consider a `someStateKey` is being used in the store state. You _may_ not be
> able to grep for it directly if it was provided only by `el.dataset`. Instead,
2021-02-22 17:27:13 +05:30
> you'd have to grep for `some_state_key`, because it could have come from a Rails
2020-04-22 19:07:51 +05:30
> template. The reverse is also true: if you're looking at a rails template, you
> might wonder what uses `some_state_key`, but you'd _have_ to grep for
2021-02-22 17:27:13 +05:30
> `someStateKey`.
2020-04-22 19:07:51 +05:30
2018-10-15 14:42:47 +05:30
### Communicating with the Store
2019-10-12 21:52:04 +05:30
2018-10-15 14:42:47 +05:30
```javascript
<script>
import { mapActions, mapState, mapGetters } from 'vuex';
export default {
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>
<template v-else>
<li
v-for="user in users"
:key="user.id"
>
{{ user }}
</li>
</template>
</ul>
</template>
```
### Testing Vuex
2019-10-12 21:52:04 +05:30
2018-10-15 14:42:47 +05:30
#### Testing Vuex concerns
2019-10-12 21:52:04 +05:30
2021-03-11 19:13:27 +05:30
Refer to [Vuex documentation](https://vuex.vuejs.org/guide/testing.html) regarding testing Actions, Getters and Mutations.
2018-10-15 14:42:47 +05:30
#### Testing components that need a store
2019-10-12 21:52:04 +05:30
2021-02-22 17:27:13 +05:30
Smaller components might use `store` properties to access the data. To write unit tests for those
components, we need to include the store and provide the correct state:
2018-10-15 14:42:47 +05:30
```javascript
//component_spec.js
import Vue from 'vue';
2020-10-24 23:57:45 +05:30
import Vuex from 'vuex';
2021-04-17 20:07:23 +05:30
import { mount } from '@vue/test-utils';
2018-11-08 19:23:39 +05:30
import { createStore } from './store';
2020-10-24 23:57:45 +05:30
import Component from './component.vue'
2021-04-17 20:07:23 +05:30
Vue.use(Vuex);
2018-10-15 14:42:47 +05:30
describe('component', () => {
2018-11-08 19:23:39 +05:30
let store;
2020-10-24 23:57:45 +05:30
let wrapper;
const createComponent = () => {
store = createStore();
wrapper = mount(Component, {
store,
});
};
2018-10-15 14:42:47 +05:30
beforeEach(() => {
2020-10-24 23:57:45 +05:30
createComponent();
2018-10-15 14:42:47 +05:30
});
afterEach(() => {
2020-10-24 23:57:45 +05:30
wrapper.destroy();
2018-10-15 14:42:47 +05:30
});
2020-10-24 23:57:45 +05:30
it('should show a user', async () => {
2018-10-15 14:42:47 +05:30
const user = {
name: 'Foo',
age: '30',
};
2018-11-20 20:47:30 +05:30
2018-10-15 14:42:47 +05:30
// populate the store
2020-10-24 23:57:45 +05:30
await store.dispatch('addUser', user);
2018-10-15 14:42:47 +05:30
2020-10-24 23:57:45 +05:30
expect(wrapper.text()).toContain(user.name);
2018-10-15 14:42:47 +05:30
});
});
```
2021-04-17 20:07:23 +05:30
Some test files may still use the
[deprecated `createLocalVue` function](https://gitlab.com/gitlab-org/gitlab/-/issues/220482)
from `@vue/test-utils` and `localVue.use(Vuex)`. This is unnecessary, and should be
avoided or removed when possible.
2020-03-13 15:44:24 +05:30
### Two way data binding
2021-02-22 17:27:13 +05:30
When storing form data in Vuex, it is sometimes necessary to update the value stored. The store
should never be mutated directly, and an action should be used instead.
To use `v-model` in our code, we need to create computed properties in this form:
2020-03-13 15:44:24 +05:30
```javascript
export default {
computed: {
someValue: {
get() {
return this.$store.state.someValue;
},
set(value) {
this.$store.dispatch("setSomeValue", value);
}
}
}
};
```
An alternative is to use `mapState` and `mapActions`:
```javascript
export default {
computed: {
...mapState(['someValue']),
localSomeValue: {
get() {
return this.someValue;
},
set(value) {
this.setSomeValue(value)
}
}
},
methods: {
...mapActions(['setSomeValue'])
}
};
```
2021-02-22 17:27:13 +05:30
Adding a few of these properties becomes cumbersome, and makes the code more repetitive with more tests to write. To simplify this there is a helper in `~/vuex_shared/bindings.js`.
2020-03-13 15:44:24 +05:30
The helper can be used like so:
```javascript
// this store is non-functional and only used to give context to the example
export default {
state: {
baz: '',
bar: '',
foo: ''
},
actions: {
2021-09-30 23:02:18 +05:30
updateBar() {...},
updateAll() {...},
2020-03-13 15:44:24 +05:30
},
getters: {
2021-09-30 23:02:18 +05:30
getFoo() {...},
2020-03-13 15:44:24 +05:30
}
}
```
```javascript
import { mapComputed } from '~/vuex_shared/bindings'
export default {
computed: {
/**
* @param {(string[]|Object[])} list - list of string matching state keys or list objects
* @param {string} list[].key - the key matching the key present in the vuex state
* @param {string} list[].getter - the name of the getter, leave it empty to not use a getter
* @param {string} list[].updateFn - the name of the action, leave it empty to use the default action
* @param {string} defaultUpdateFn - the default function to dispatch
2021-09-30 23:02:18 +05:30
* @param {string|function} root - optional key of the state where to search for they keys described in list
2020-03-13 15:44:24 +05:30
* @returns {Object} a dictionary with all the computed properties generated
*/
...mapComputed(
[
'baz',
2021-09-30 23:02:18 +05:30
{ key: 'bar', updateFn: 'updateBar' },
2020-03-13 15:44:24 +05:30
{ key: 'foo', getter: 'getFoo' },
],
'updateAll',
),
}
}
```
2021-02-22 17:27:13 +05:30
`mapComputed` then generates the appropriate computed properties that get the data from the store and dispatch the correct action when updated.
2021-09-30 23:02:18 +05:30
In the event that the `root` of the key is more than one-level deep you can use a function to retrieve the relevant state object.
For instance, with a store like:
```javascript
// this store is non-functional and only used to give context to the example
export default {
state: {
foo: {
qux: {
baz: '',
bar: '',
foo: '',
},
},
},
actions: {
updateBar() {...},
updateAll() {...},
},
getters: {
getFoo() {...},
}
}
```
The `root` could be:
```javascript
import { mapComputed } from '~/vuex_shared/bindings'
export default {
computed: {
...mapComputed(
[
'baz',
{ key: 'bar', updateFn: 'updateBar' },
{ key: 'foo', getter: 'getFoo' },
],
'updateAll',
(state) => state.foo.qux,
),
}
}
```