From fef1e9d47b1e522293ed3c5a8b3b241df2246b27 Mon Sep 17 00:00:00 2001 From: Filipa Lacerda Date: Thu, 22 Mar 2018 10:25:03 +0000 Subject: [PATCH 1/5] Improve state management documentation --- doc/development/fe_guide/vue.md | 262 ++----------------------------- doc/development/fe_guide/vuex.md | 261 ++++++++++++++++++++++++++++++ 2 files changed, 275 insertions(+), 248 deletions(-) create mode 100644 doc/development/fe_guide/vuex.md diff --git a/doc/development/fe_guide/vue.md b/doc/development/fe_guide/vue.md index c1170fa3b13..3b68fd858cc 100644 --- a/doc/development/fe_guide/vue.md +++ b/doc/development/fe_guide/vue.md @@ -1,29 +1,7 @@ # Vue -For more complex frontend features, we recommend using Vue.js. It shares -some ideas with React.js as well as Angular. - To get started with Vue, read through [their documentation][vue-docs]. -## When to use Vue.js - -We recommend using Vue for more complex features. Here are some guidelines for when to use Vue.js: - -- If you are starting a new feature or refactoring an old one that highly interacts with the DOM; -- For real time data updates; -- If you are creating a component that will be reused elsewhere; - -## When not to use Vue.js - -We don't want to refactor all GitLab frontend code into Vue.js, here are some guidelines for -when not to use Vue.js: - -- Adding or changing static information; -- Features that highly depend on jQuery will be hard to work with Vue.js; -- Features without reactive data; - -As always, the Frontend Architectural Experts are available to help with any Vue or JavaScript questions. - ## Vue architecture All new features built with Vue.js must follow a [Flux architecture][flux]. @@ -57,15 +35,15 @@ new_feature │ └── ... ├── stores │ └── new_feature_store.js -├── services +├── services # only when not using vuex │ └── new_feature_service.js -├── new_feature_bundle.js +├── index.js ``` _For consistency purposes, we recommend you to follow the same structure._ Let's look into each of them: -### A `*_bundle.js` file +### A `index.js` file This is the index file of your new feature. This is where the root Vue instance of the new feature should be. @@ -144,30 +122,15 @@ in one table would not be a good use of this pattern. You can read more about components in Vue.js site, [Component System][component-system] #### Components Gotchas -1. Using SVGs in components: To use an SVG in a template we need to make it a property we can access through the component. -A `prop` and a property returned by the `data` functions require `vue` to set a `getter` and a `setter` for each of them. -The SVG should be a computed property in order to improve performance, note that computed properties are cached based on their dependencies. - -```javascript -// bad -import svg from 'svg.svg'; -data() { - return { - myIcon: svg, - }; -}; - -// good -import svg from 'svg.svg'; -computed: { - myIcon() { - return svg; - } -} -``` +1. Using SVGs icons in components: To use an SVG icon in a template use the `icon.vue` +1. Using SVGs illustrations in components: To use an SVG illustrations in a template provide the path as a prop. ### A folder for the Store +#### Vuex +Check this [page](vuex.md) for more details. + +#### Flux like state management The Store is a class that allows us to manage the state in a single source of truth. It is not aware of the service or the components. @@ -176,6 +139,8 @@ itself, please read this guide: [State Management][state-management] ### A folder for the Service +**If you are using Vuex you won't need this step** + The Service is a class used only to communicate with the server. It does not store or manipulate any data. It is not aware of the store or the components. We use [axios][axios] to communicate with the server. @@ -273,6 +238,9 @@ import Store from 'store'; import Service from 'service'; import TodoComponent from 'todoComponent'; export default { + components: { + todo: TodoComponent, + }, /** * Although most data belongs in the store, each component it's own state. * We want to show a loading spinner while we are fetching the todos, this state belong @@ -291,10 +259,6 @@ export default { }; }, - components: { - todo: TodoComponent, - }, - created() { this.service = new Service('todos'); @@ -476,200 +440,6 @@ need to test the rendered output. [Vue][vue-test] guide's to unit test show us e Refer to [mock axios](axios.md#mock-axios-response-on-tests) -## Vuex -To manage the state of an application you may use [Vuex][vuex-docs]. - -_Note:_ All of the below is explained in more detail in the official [Vuex documentation][vuex-docs]. - -### Separation of concerns -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. - -#### File structure -When using Vuex at GitLab, separate this concerns into different files to improve readability. If you can, separate the Mutation Types as well: - -``` -└── store - ├── index.js # where we assemble modules and export the store - ├── actions.js # actions - ├── mutations.js # mutations - ├── getters.js # getters - └── mutation_types.js # mutation types -``` -The following examples show an application that lists and adds users to the state. - -##### `index.js` -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'; - -Vue.use(Vuex); - -export default new Vuex.Store({ - actions, - getters, - mutations, - state: { - users: [], - }, -}); -``` -_Note:_ If the state of the application is too complex, an individual file for the state may be better. - -#### `actions.js` -An action commits a mutatation. In this file, we will write the actions that will call the respective mutation: - -```javascript - import * as types from './mutation_types'; - - export const addUser = ({ commit }, user) => { - commit(types.ADD_USER, user); - }; -``` - -To dispatch an action from a component, use the `mapActions` helper: -```javascript -import { mapActions } from 'vuex'; - -{ - methods: { - ...mapActions([ - 'addUser', - ]), - onClickUser(user) { - this.addUser(user); - }, - }, -}; -``` - -#### `getters.js` -Sometimes we may need to get derived state based on store state, like filtering for a specific prop. This can be done through the `getters`: - -```javascript -// get all the users with pets -export getUsersWithPets = (state, getters) => { - return state.users.filter(user => user.pet !== undefined); -}; -``` - -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 * as types from './mutation_types'; - - export default { - [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 -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: -```javascript - // app.vue - import store from 'store'; // it will include the index.js file - - export default { - 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: - -```javascript -//component_spec.js -import Vue from 'vue'; -import store from './store'; -import component from './component.vue' - -describe('component', () => { - let vm; - let Component; - - beforeEach(() => { - Component = Vue.extend(issueActions); - }); - - afterEach(() => { - vm.$destroy(); - }); - - it('should show a user', () => { - const user = { - name: 'Foo', - age: '30', - }; - - // populate the store - store.dipatch('addUser', user); - - vm = new Component({ - store, - propsData: props, - }).$mount(); - }); -}); -``` [vue-docs]: http://vuejs.org/guide/index.html [issue-boards]: https://gitlab.com/gitlab-org/gitlab-ce/tree/master/app/assets/javascripts/boards @@ -681,9 +451,5 @@ describe('component', () => { [vue-test]: https://vuejs.org/v2/guide/unit-testing.html [issue-boards-service]: https://gitlab.com/gitlab-org/gitlab-ce/blob/master/app/assets/javascripts/boards/services/board_service.js.es6 [flux]: https://facebook.github.io/flux -[vuex-docs]: https://vuex.vuejs.org -[vuex-structure]: https://vuex.vuejs.org/en/structure.html -[vuex-mutations]: https://vuex.vuejs.org/en/mutations.html -[vuex-testing]: https://vuex.vuejs.org/en/testing.html [axios]: https://github.com/axios/axios [axios-interceptors]: https://github.com/axios/axios#interceptors diff --git a/doc/development/fe_guide/vuex.md b/doc/development/fe_guide/vuex.md new file mode 100644 index 00000000000..faa7e44f8bf --- /dev/null +++ b/doc/development/fe_guide/vuex.md @@ -0,0 +1,261 @@ + +## Vuex +To manage the state of an application you may use [Vuex][vuex-docs]. + +_Note:_ All of the below is explained in more detail in the official [Vuex documentation][vuex-docs]. + +### Separation of concerns +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. + +#### File structure +When using Vuex at GitLab, separate this concerns into different files to improve readability. If you can, separate the Mutation Types as well: + +``` +└── store + ├── index.js # where we assemble modules and export the store + ├── actions.js # actions + ├── mutations.js # mutations + ├── getters.js # getters + └── mutation_types.js # mutation types +``` +The following examples show an application that lists and adds users to the state. + +##### `index.js` +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'; + +Vue.use(Vuex); + +export default new Vuex.Store({ + actions, + getters, + mutations, + state: { + users: [], + }, +}); +``` +_Note:_ If the state of the application is too complex, an individual file for the state may be better. + +#### `actions.js` +An action is a playload of information to send data from our application to our store. +They are the only source of information for the store. + +An action is usually composed by a `type` and a `payload` and they describe what happened. +By enforcing that every change is described as an action lets us have a clear understantid of what is going on in the app. + +An action represents something that will trigger a state change, for example, when the user enters the page we need to load resources. + +In this file, we will write the actions (both sync and async) that will call the respective mutations: + +```javascript + import * as types from './mutation_types'; + import axios from '~/lib/utils/axios-utils'; + + export const requestUsers = ({ commit }) => commit(types.REQUEST_USERS); + export const receiveUsersSuccess = ({ commit }, data) => commit(types.RECEIVE_USERS_SUCCESS, data); + export const receiveUsersError = ({ commit }, error) => commit(types.REQUEST_USERS_ERROR, error); + + export const fetchUsers = ({ state, dispatch }) => { + dispatch('requestUsers'); + + axios.get(state.endoint) + .then(({ data }) => dispatch('receiveUsersSuccess', data)) + .catch((error) => dispatch('receiveUsersError', error)); + } + + 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'); + + axios.post(state.endoint, user) + .then(({ data }) => dispatch('receiveAddUserSuccess', data)) + .catch((error) => dispatch('receiveAddUserError', error)); + } + +``` + +##### Actions 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 action to toggle the loading state and dispatch it in the component, +create: +1. A sync action `requestSomething`, to toggle the loading state +1. A sync action `receiveSomethingSuccess`, to handle the success callback +1. A sync action `receiveSomethingError`, to handle the error callback +1. An async action `fetchSomething` to make the request. + +The component MUST only dispatch the `fetchNamespace` action. +The `fetch` action will be responsible to dispatch `requestNamespace`, `receiveNamespaceSuccess` and `receiveNamespaceError` + +By following this patter we guarantee: +1. All aplications 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. Actions are contained and human friendly +1. Unit tests are easier +1. Actions are simple and straightforward + +##### Dispatching actions +To dispatch an action from a component, use the `mapActions` helper: +```javascript +import { mapActions } from 'vuex'; + +{ + methods: { + ...mapActions([ + 'addUser', + ]), + onClickUser(user) { + this.addUser(user); + }, + }, +}; +``` + +#### `mutations.js` +The mutations specify how the application state changes in response to actions sent to the store. +The only way to actually change state in a Vuex store is by committing a mutation. + +**It's a good idea to think of the state shape before writing any code.** + +Remember that actions only describe the fact that something happened, they don't describe how the application state changes. + +**Never commit a mutation directly from a component** + +```javascript + import * as types from './mutation_types'; + + export default { + [types.ADD_USER](state, user) { + state.users.push(user); + }, + }; +``` + + + +#### `getters.js` +Sometimes we may need to get derived state based on store state, like filtering for a specific prop. +This can be done through the `getters`: + +```javascript +// get all the users with pets +export getUsersWithPets = (state, getters) => { + return state.users.filter(user => user.pet !== undefined); +}; +``` + +To access a getter from a component, use the `mapGetters` helper: +```javascript +import { mapGetters } from 'vuex'; + +{ + computed: { + ...mapGetters([ + 'getUsersWithPets', + ]), + }, +}; +``` + +#### `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 +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: +```javascript + // app.vue + import store from 'store'; // it will include the index.js file + + export default { + name: 'application', + store, + ... + }; +``` + +### Vuex Gotchas +1. Do not call 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. 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'; +import store from './store'; +import component from './component.vue' + +describe('component', () => { + let vm; + let Component; + + beforeEach(() => { + Component = Vue.extend(issueActions); + }); + + afterEach(() => { + vm.$destroy(); + }); + + it('should show a user', () => { + const user = { + name: 'Foo', + age: '30', + }; + + // populate the store + store.dipatch('addUser', user); + + vm = new Component({ + store, + propsData: props, + }).$mount(); + }); +}); +``` + +[vuex-docs]: https://vuex.vuejs.org +[vuex-structure]: https://vuex.vuejs.org/en/structure.html +[vuex-mutations]: https://vuex.vuejs.org/en/mutations.html +[vuex-testing]: https://vuex.vuejs.org/en/testing.html \ No newline at end of file From dd3b1526af1675f7686f189ec41b8d919b6835a2 Mon Sep 17 00:00:00 2001 From: Filipa Lacerda Date: Thu, 22 Mar 2018 10:50:52 +0000 Subject: [PATCH 2/5] Fixes typos and adds mutations examples --- doc/development/fe_guide/index.md | 5 ++ doc/development/fe_guide/vuex.md | 131 +++++++++++++++++++++++++----- 2 files changed, 117 insertions(+), 19 deletions(-) diff --git a/doc/development/fe_guide/index.md b/doc/development/fe_guide/index.md index 2280cf79f86..73084d667d4 100644 --- a/doc/development/fe_guide/index.md +++ b/doc/development/fe_guide/index.md @@ -73,6 +73,11 @@ Vue specific design patterns and practices. --- +## [Vuex](vuex.md) +Vuex specific design patterns and practices. + +--- + ## [Axios](axios.md) Axios specific practices and gotchas. diff --git a/doc/development/fe_guide/vuex.md b/doc/development/fe_guide/vuex.md index faa7e44f8bf..69f4588fafe 100644 --- a/doc/development/fe_guide/vuex.md +++ b/doc/development/fe_guide/vuex.md @@ -1,17 +1,16 @@ - -## Vuex +# Vuex To manage the state of an application you may use [Vuex][vuex-docs]. _Note:_ All of the below is explained in more detail in the official [Vuex documentation][vuex-docs]. -### Separation of concerns +## Separation of concerns 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. -#### File structure -When using Vuex at GitLab, separate this concerns into different files to improve readability. If you can, separate the Mutation Types as well: +## File structure +When using Vuex at GitLab, separate this concerns into different files to improve readability: ``` └── store @@ -19,11 +18,12 @@ When using Vuex at GitLab, separate this concerns into different files to improv ├── actions.js # actions ├── mutations.js # mutations ├── getters.js # getters + ├── state.js # getters └── mutation_types.js # mutation types ``` -The following examples show an application that lists and adds users to the state. +The following example shows an application that lists and adds users to the state. -##### `index.js` +### `index.js` This is the entry point for our store. You can use the following as a guide: ```javascript @@ -32,6 +32,7 @@ import Vuex from 'vuex'; import * as actions from './actions'; import * as getters from './getters'; import mutations from './mutations'; +import state from './state'; Vue.use(Vuex); @@ -39,19 +40,38 @@ export default new Vuex.Store({ actions, getters, mutations, - state: { - users: [], - }, + state, }); ``` -_Note:_ If the state of the application is too complex, an individual file for the state may be better. -#### `actions.js` +### `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 + export default { + endpoint: null, + + isLoading: false, + error: null, + + isAddingUser: false, + errorAddingUser: false, + + users: [], + }; +``` + +#### Access `state` properties +You can use `mapState` to access state properties in the components. + +### `actions.js` An action is a playload of information to send data from our application to our store. They are the only source of information for the store. An action is usually composed by a `type` and a `payload` and they describe what happened. -By enforcing that every change is described as an action lets us have a clear understantid of what is going on in the app. +Enforcing that every change is described as an action lets us have a clear understanting of what is going on in the app. An action represents something that will trigger a state change, for example, when the user enters the page we need to load resources. @@ -84,10 +104,9 @@ In this file, we will write the actions (both sync and async) that will call the .then(({ data }) => dispatch('receiveAddUserSuccess', data)) .catch((error) => dispatch('receiveAddUserError', error)); } - ``` -##### Actions Pattern: `request` and `receive` namespaces +#### Actions 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 action to toggle the loading state and dispatch it in the component, @@ -107,7 +126,7 @@ By following this patter we guarantee: 1. Unit tests are easier 1. Actions are simple and straightforward -##### Dispatching actions +#### Dispatching actions To dispatch an action from a component, use the `mapActions` helper: ```javascript import { mapActions } from 'vuex'; @@ -124,6 +143,9 @@ import { mapActions } from 'vuex'; }; ``` +#### Handling errors with `createFlash` +// TODO + #### `mutations.js` The mutations specify how the application state changes in response to actions sent to the store. The only way to actually change state in a Vuex store is by committing a mutation. @@ -138,14 +160,29 @@ Remember that actions only describe the fact that something happened, they don't import * as types from './mutation_types'; export default { - [types.ADD_USER](state, user) { + [types.REQUEST_USERS](state) { + Object.assign(state, { isLoading: true }); + }, + [types.RECEIVE_USERS_SUCCESS](state, data) { + // Do any needed data transformation to the received payload here + Object.assign(state, { users: data, isLoading: false }); + }, + [types.REQUEST_USERS_ERROR](state, error) { + Object.assign(state, { isLoading: false, error}); + }, + [types.REQUEST_ADD_USER](state, user) { + Object.assign(state, { isAddingUser: true }); + }, + [types.RECEIVE_ADD_USER_SUCCESS](state, user) { + Object.assign(state, { isAddingUser: false }); state.users.push(user); }, + [types.REQUEST_ADD_USER_ERROR](state, error) { + Object.assign(state, { isAddingUser: true , errorAddingUser: error}); + }, }; ``` - - #### `getters.js` Sometimes we may need to get derived state based on store state, like filtering for a specific prop. This can be done through the `getters`: @@ -191,6 +228,62 @@ The store should be included in the main component of your application: }; ``` +### Communicating with the Store +```javascript + + +``` + ### Vuex Gotchas 1. Do not call a mutation directly. Always use an action to commit a mutation. Doing so will keep consistency through out the application. From Vuex docs: From 44376b3007deb1d27e59eee1a8704353a960c144 Mon Sep 17 00:00:00 2001 From: Filipa Lacerda Date: Wed, 4 Apr 2018 20:15:04 +0100 Subject: [PATCH 3/5] Changes after review --- doc/development/fe_guide/vuex.md | 65 ++++++++++++++++---------------- 1 file changed, 33 insertions(+), 32 deletions(-) diff --git a/doc/development/fe_guide/vuex.md b/doc/development/fe_guide/vuex.md index 69f4588fafe..56e26fd34b9 100644 --- a/doc/development/fe_guide/vuex.md +++ b/doc/development/fe_guide/vuex.md @@ -18,7 +18,7 @@ When using Vuex at GitLab, separate this concerns into different files to improv ├── actions.js # actions ├── mutations.js # mutations ├── getters.js # getters - ├── state.js # getters + ├── state.js # state └── mutation_types.js # mutation types ``` The following example shows an application that lists and adds users to the state. @@ -68,18 +68,16 @@ You can use `mapState` to access state properties in the components. ### `actions.js` An action is a playload of information to send data from our application to our store. -They are the only source of information for the store. An action is usually composed by a `type` and a `payload` and they describe what happened. Enforcing that every change is described as an action lets us have a clear understanting of what is going on in the app. -An action represents something that will trigger a state change, for example, when the user enters the page we need to load resources. - -In this file, we will write the actions (both sync and async) that will call the respective mutations: +In this file, we will write the actions that will call the respective mutations: ```javascript import * as types from './mutation_types'; import axios from '~/lib/utils/axios-utils'; + import createFlash from '~/flash'; export const requestUsers = ({ commit }) => commit(types.REQUEST_USERS); export const receiveUsersSuccess = ({ commit }, data) => commit(types.RECEIVE_USERS_SUCCESS, data); @@ -90,7 +88,10 @@ In this file, we will write the actions (both sync and async) that will call the axios.get(state.endoint) .then(({ data }) => dispatch('receiveUsersSuccess', data)) - .catch((error) => dispatch('receiveUsersError', error)); + .catch((error) => { + dispatch('receiveUsersError', error) + createFlash('There was an error') + }); } export const requestAddUser = ({ commit }) => commit(types.REQUEST_ADD_USER); @@ -111,15 +112,15 @@ 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: -1. A sync action `requestSomething`, to toggle the loading state -1. A sync action `receiveSomethingSuccess`, to handle the success callback -1. A sync action `receiveSomethingError`, to handle the error callback -1. An async action `fetchSomething` to make the request. +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 +1. An action `fetchSomething` to make the request. The component MUST only dispatch the `fetchNamespace` action. The `fetch` action will be responsible to dispatch `requestNamespace`, `receiveNamespaceSuccess` and `receiveNamespaceError` -By following this patter we guarantee: +By following this pattern we guarantee: 1. All aplications 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. Actions are contained and human friendly @@ -148,11 +149,11 @@ import { mapActions } from 'vuex'; #### `mutations.js` The mutations specify how the application state changes in response to actions sent to the store. -The only way to actually change state in a Vuex store is by committing a mutation. +The only way to change state in a Vuex store should be by committing a mutation. -**It's a good idea to think of the state shape before writing any code.** +**It's a good idea to think of the state before writing any code.** -Remember that actions only describe the fact that something happened, they don't describe how the application state changes. +Remember that actions only describe that something happened, they don't describe how the application state changes. **Never commit a mutation directly from a component** @@ -161,24 +162,26 @@ Remember that actions only describe the fact that something happened, they don't export default { [types.REQUEST_USERS](state) { - Object.assign(state, { isLoading: true }); + state.isLoading = true; }, [types.RECEIVE_USERS_SUCCESS](state, data) { // Do any needed data transformation to the received payload here - Object.assign(state, { users: data, isLoading: false }); + state.users = data; + state.isLoading = false; }, [types.REQUEST_USERS_ERROR](state, error) { - Object.assign(state, { isLoading: false, error}); + state.isLoading = false; }, [types.REQUEST_ADD_USER](state, user) { - Object.assign(state, { isAddingUser: true }); + state.isAddingUser = true; }, [types.RECEIVE_ADD_USER_SUCCESS](state, user) { - Object.assign(state, { isAddingUser: false }); + state.isAddingUser = false; state.users.push(user); }, [types.REQUEST_ADD_USER_ERROR](state, error) { - Object.assign(state, { isAddingUser: true , errorAddingUser: error}); + state.isAddingUser = true; + state.errorAddingUser = error∂; }, }; ``` @@ -189,7 +192,7 @@ This can be done through the `getters`: ```javascript // get all the users with pets -export getUsersWithPets = (state, getters) => { +export const getUsersWithPets = (state, getters) => { return state.users.filter(user => user.pet !== undefined); }; ``` @@ -259,9 +262,6 @@ export default { created() { this.fetchUsers() - .catch(() => { - // TODO - Decide where to handle the `createFlash` - }) } } @@ -273,13 +273,14 @@ export default {
  • {{ error }}
  • -
  • - {{ user }} -
  • + ``` @@ -351,4 +352,4 @@ describe('component', () => { [vuex-docs]: https://vuex.vuejs.org [vuex-structure]: https://vuex.vuejs.org/en/structure.html [vuex-mutations]: https://vuex.vuejs.org/en/mutations.html -[vuex-testing]: https://vuex.vuejs.org/en/testing.html \ No newline at end of file +[vuex-testing]: https://vuex.vuejs.org/en/testing.html From 703f45632292e7fc45359d0144cd616725bf9b0d Mon Sep 17 00:00:00 2001 From: Filipa Lacerda Date: Fri, 6 Apr 2018 08:38:19 +0000 Subject: [PATCH 4/5] Update vuex.md --- doc/development/fe_guide/vuex.md | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/doc/development/fe_guide/vuex.md b/doc/development/fe_guide/vuex.md index 56e26fd34b9..7298ffcd54a 100644 --- a/doc/development/fe_guide/vuex.md +++ b/doc/development/fe_guide/vuex.md @@ -115,9 +115,13 @@ create: 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 -1. An action `fetchSomething` to make the request. +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: + 1. `PUT`: `createSomething` + 2. `POST`: `updateSomething` + 3. `DELETE`: `deleteSomething` -The component MUST only dispatch the `fetchNamespace` action. +The component MUST only dispatch the `fetchNamespace` action. Actions namespaced with `request` or `receive` should not be called from the component The `fetch` action will be responsible to dispatch `requestNamespace`, `receiveNamespaceSuccess` and `receiveNamespaceError` By following this pattern we guarantee: @@ -144,9 +148,6 @@ import { mapActions } from 'vuex'; }; ``` -#### Handling errors with `createFlash` -// TODO - #### `mutations.js` The mutations specify how the application state changes in response to actions sent to the store. The only way to change state in a Vuex store should be by committing a mutation. From d453257ff3a654b02f6d39f882a81c5d2a823750 Mon Sep 17 00:00:00 2001 From: Filipa Lacerda Date: Mon, 7 May 2018 10:09:49 +0100 Subject: [PATCH 5/5] Follow up after review --- doc/development/fe_guide/vue.md | 17 ++++++++++++++++- doc/development/fe_guide/vuex.md | 2 ++ 2 files changed, 18 insertions(+), 1 deletion(-) diff --git a/doc/development/fe_guide/vue.md b/doc/development/fe_guide/vue.md index 62c3a05eb3b..f971d8b7388 100644 --- a/doc/development/fe_guide/vue.md +++ b/doc/development/fe_guide/vue.md @@ -123,7 +123,22 @@ You can read more about components in Vue.js site, [Component System][component- #### Components Gotchas 1. Using SVGs icons in components: To use an SVG icon in a template use the `icon.vue` -1. Using SVGs illustrations in components: To use an SVG illustrations in a template provide the path as a prop. +1. Using SVGs illustrations in components: To use an SVG illustrations in a template provide the path as a prop and display it through a standard img tag. + ```javascript +