create account

Universal Vue.js application with Nuxt.js part#6 Create Store in Vuex, Request data in Vuex, Data centralized by duski.harahap

View this thread on: hive.blogpeakd.comecency.com
· @duski.harahap ·
$78.35
Universal Vue.js application with Nuxt.js part#6 Create Store in Vuex, Request data in Vuex, Data centralized
![Screenshot_11.png](https://ipfs.busy.org/ipfs/QmfD4iXQxMDHGeAqT1wfGHKn3aczoKgV9CwSDToTnj7v8e)

#### Repository
https://github.com/nuxt/nuxt.js

#### What Will I Learn?
- Create Store in Vuex
- Request data in Vuex
- Making the data centralized
- Using Vuex on component

#### Resources
- Nuxt.js Website - https://nuxtjs.org/
- Nuxt.js Github. - https://github.com/nuxt/nuxt.js
- Axios- https://github.com/axios/axios
- JSON Placeholder- https://jsonplaceholder.typicode.com/
- Vuex - https://github.com/vuejs/vuex


#### Difficulty
Intermediated

### Tutorial Contents

This tutorial is a tutorial on the continuation of the previous [tutorial](https://steemit.com/utopian-io/@duski.harahap/universal-vue-js-application-with-nuxt-js-part-5-create-database-api-request-data-setup-port-database-and-nuxt-js-application), we will learn about ***Vuex*** in Nuxt.js, for those of you who are familiar with Vue.js, of course, you already know the ***state management*** in **Vue.js**. When we install **Nuxt.js** then automatically we have also installed Vuex, therefore we do not need to install it again, we will make the state management in the folder **store** in Nuxt.js, with Vuex we will not process the data of a component but we will process it on the store in Vuex. for more details we just see how to use and best practice.

### Data centralization
The idea of using **state management (Vuex)** is that data can be centralized and can be used or processed in any component. maybe if the data we use is not too big, we do not have to use Vuex, but if your data is large and usage is used massively, then we need a state management that is Vuex. 

- **Create store in Vuex**

We will create a file that will be used to process the data, we can create the default file is **index.js** in the store folder. 
**index.js**
``` javascript
import axios from '~/plugins/axios'
export const state = () => ({
	countries : []
});
export const mutations = {
	setData(state, items){
		state.countries = items
	}
}
export const actions = {
	async nuxtServerInit ({commit}){
		const res = await axios.get('country')
		commit('setData', res.data)
	}
}
```
```import axios from '~/plugins/axios'``` we must import axios first to be able to use it.


- **State** 

```export const state = () => ({ });``` we will create a ```const``` with the **state** name and export it, the state is a data source that we will use in the component. We can create a variable in the form of ***string, int, array, or object***.

- **Mutations**

```export const mutations = { }``` we will create a ```const``` with the **mutations** name and export it, the usefulness of **mutations** is to change the data in the **state**, so that the process of data changes will occur within mutations. We can generate a function in mutations with mandatory parameters ie state and we can also provide additional parameters as usual. 

**Example:**

```setData(state, items){ }```

```state``` is a mandatory parameter because the task of **mutations** is to change the data in the state, ```setData ()``` is a function in mutations that we can call in **actions**. In this tutorial, on the ```setData()```, we pass additional parameters ie **items**, items are data that is successfully retrieved from the database and pass on the commit data in the action ```commit('setData', res.data)```.

- **Actions**

```export const actions = { }``` we will create a ```const``` with the **actions** name and export it, ```actions``` are useful for processing the data whose results will be **committed** in **mutations**, so basically actions can not directly change **states**, **actions** will commit in mutations and mutations that will change state. We can write the action ```function()``` as usual, but in this tutorial, I use the ```nuxtServerInit``` function of nuxt.js to run the first time when our nuxt.js app is rendered.

**Example:**
``` javascript
async nuxtServerInit ({commit}){
		const res = await axios.get('country')
		commit('setData', res.data)
	}
}
```
There is a mandatory parameter that exists in every action function that is **commit**, this parameter serves to commit to **function in mutations**. In this tutorial, we will commit to ```setData()``` function.   ```const data = await axios.get('country')``` This is the endpoint of the **API** we have created in the previous [tutorial](https://steemit.com/utopian-io/@duski.harahap/universal-vue-js-application-with-nuxt-js-part-5-create-database-api-request-data-setup-port-database-and-nuxt-js-application), we have set **BaseURL localhost:3000** and the location of the data is on **localhost: 3000/country**. so we just need to add **'country'** on request axios.

We can see the data is successfully retrieved from the API, in the existing command prompt running in our Nuxt.js application.

![Screenshot_9.png](https://ipfs.busy.org/ipfs/QmWptDS7f7ZJvvCzjWL3TNmnENZhmW4BZbbJZVSDvfkxu4)
<br>
- **Use Vuex in Component**

We have learned how to the concept on **Store**, now we will use State part of the component.  We will compare the **index.vue** that **uses Vuex** and which d**o not use Vuex**.

- **Before**

``` html
<template>
  <div>
    <div style="text-align: center;">
      <app-logo/>
      <h1 class="title">
        millenuxt
      </h1>
      <h2 class="subtitle">
        Vuex in Nuxt.js
      </h2>
      <div class="alert alert-primary" role="alert" v-for="item in countries" :key="item.id">
         <p>Country : {{item.name}}</p> 
         <p>Capital City: {{item.city}}</p>
      </div>
    </div>
  </div>
</template>
<script>
  import AppLogo from '~/components/AppLogo.vue'
  export default{
    components: {
      AppLogo
    },
    asyncData(){
        return axios.get('country').then(res=>({
          countries: res.data
        }))
    }
  }
</script>
```
<br>
- **After:**
``` html
<template>
  <div>
    <div style="text-align: center;">
      <app-logo/>
      <h1 class="title">
        millenuxt
      </h1>
      <h2 class="subtitle">
        Vuex in Nuxt.js
      </h2>
      <div class="alert alert-primary" role="alert" v-for="item in countries" :key="item.id">
         <p>Country : {{item.name}}</p> 
         <p>Capital City: {{item.city}}</p>
      </div>
    </div>
  </div>
</template>
<script>
  import AppLogo from '~/components/AppLogo.vue'
  import {mapState} from 'vuex'
  export default{
    components: {
      AppLogo
    },
    computed: mapState([
      'countries'
    ])  
  }
</script>
```

- We can see that before we use **Vuex** we do the async request process on the component part and if we use **Vuex** we separate the **API** request process in the **Actions** section in **Store/index.js**.

- Using Vuex means we must first import mapState from vuex ``` import {mapState} from 'vuex'``` and we put the **mapState** value on the ```computed:{}``` property so that data changes can automatically.

- The result will not be different, the difference is only in the data process, although the use of ***state management*** is more complicated, this will greatly help us when the data in need a lot. we do not need to run the process in every component but only once data processing can be used in every component.  to test the application we have created, do not forget to run the database API.

**database  localhost:3000** 

![Screenshot_8.png](https://ipfs.busy.org/ipfs/QmZXo54TKrQfqCFxgvR2GUNdWqi1VUzm3DxEXYMuKZEMtL)

**Nuxt.js app on localhost:3333**

![Screenshot_10.png](https://ipfs.busy.org/ipfs/QmaeP6BB9sdvKWBirqq46fxSSRYtcPfAmeqw5HNvw6nPmf)
<br>
![Vuex.gif](https://ipfs.busy.org/ipfs/QmXoPoQSe9vBW9CNibYjwbHja8HKBazVVYbu2KjP8qYDDb)

We can see the result as the picture above we succeeded in moving the previous process in the component, now we have changed using Vuex and the data we can be centralized, so if the data is changed then all components using the data will also change. just so much my tutorial about the state management of VUE. hopefully, this tutorial helps you thank you.

### Curriculum
[Learn Nuxt#1 Nuxt structure, Global CSS, Request API](https://steemit.com/utopian-io/@duski.harahap/universal-vue-js-application-with-nuxt-js-part-1-nuxt-structure-installation-and-configuration-global-css-and-css-frameworks)
[Learn Nuxt#2 Vuex in Nuxt.js, Classic Mode and Modules Mode](https://steemit.com/utopian-io/@duski.harahap/universal-vue-js-application-with-nuxt-js-part-1-vuex-in-nuxt-js-classic-mode-and-modules-mode)
[Learn Nuxt#3 Create components, Reusable components and Nuxt-link](https://steemit.com/utopian-io/@duski.harahap/universal-vue-js-application-with-nuxt-js-part-3-create-components-in-nuxt-js-reusable-components-nuxt-link)
[Learn Nuxt#4 Dynamic components, Props, Transition page, Dynamic pages](https://steemit.com/utopian-io/@duski.harahap/universal-vue-js-application-with-nuxt-js-part-4-dynamic-components-props-transition-page-dynamic-pages)
[Learn Nuxt#5 Create Database API, Request data, Setup Port](https://steemit.com/utopian-io/@duski.harahap/universal-vue-js-application-with-nuxt-js-part-5-create-database-api-request-data-setup-port-database-and-nuxt-js-application)

#### Proof of Work Done
https://github.com/milleaduski/learnNuxtjs
πŸ‘  , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , and 27 others
properties (23)
authorduski.harahap
permlinkuniversal-vue-js-application-with-nuxt-js-part-6-create-store-in-vuex-request-data-in-vuex-data-centralized
categoryutopian-io
json_metadata{"community":"busy","app":"busy/2.5.2","format":"markdown","links":["https://github.com/nuxt/nuxt.js","https://nuxtjs.org/","https://github.com/nuxt/nuxt.js","https://github.com/axios/axios","https://jsonplaceholder.typicode.com/","https://github.com/vuejs/vuex","https://steemit.com/utopian-io/@duski.harahap/universal-vue-js-application-with-nuxt-js-part-5-create-database-api-request-data-setup-port-database-and-nuxt-js-application","https://steemit.com/utopian-io/@duski.harahap/universal-vue-js-application-with-nuxt-js-part-5-create-database-api-request-data-setup-port-database-and-nuxt-js-application","https://steemit.com/utopian-io/@duski.harahap/universal-vue-js-application-with-nuxt-js-part-1-nuxt-structure-installation-and-configuration-global-css-and-css-frameworks","https://steemit.com/utopian-io/@duski.harahap/universal-vue-js-application-with-nuxt-js-part-1-vuex-in-nuxt-js-classic-mode-and-modules-mode"],"users":["duski.harahap"],"tags":["utopian-io","tutorials","nuxtjs","vuejs","javascript"],"image":["https://ipfs.busy.org/ipfs/QmfD4iXQxMDHGeAqT1wfGHKn3aczoKgV9CwSDToTnj7v8e","https://ipfs.busy.org/ipfs/QmWptDS7f7ZJvvCzjWL3TNmnENZhmW4BZbbJZVSDvfkxu4","https://ipfs.busy.org/ipfs/QmZXo54TKrQfqCFxgvR2GUNdWqi1VUzm3DxEXYMuKZEMtL","https://ipfs.busy.org/ipfs/QmaeP6BB9sdvKWBirqq46fxSSRYtcPfAmeqw5HNvw6nPmf","https://ipfs.busy.org/ipfs/QmXoPoQSe9vBW9CNibYjwbHja8HKBazVVYbu2KjP8qYDDb"]}
created2018-07-16 15:08:03
last_update2018-07-16 15:08:03
depth0
children3
last_payout2018-07-23 15:08:03
cashout_time1969-12-31 23:59:59
total_payout_value59.267 HBD
curator_payout_value19.081 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length9,202
author_reputation60,094,717,098,672
root_title"Universal Vue.js application with Nuxt.js part#6 Create Store in Vuex, Request data in Vuex, Data centralized"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id64,880,613
net_rshares36,726,033,378,661
author_curate_reward""
vote details (91)
@jazz10 ·
Very well explained !thanks for sharing knowledgeable post
properties (22)
authorjazz10
permlinkre-duskiharahap-universal-vue-js-application-with-nuxt-js-part-6-create-store-in-vuex-request-data-in-vuex-data-centralized-20180716t152955672z
categoryutopian-io
json_metadata{"tags":["utopian-io"],"app":"steemit/0.1"}
created2018-07-16 15:29:57
last_update2018-07-16 15:29:57
depth1
children0
last_payout2018-07-23 15:29:57
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length58
author_reputation80,438,762,310
root_title"Universal Vue.js application with Nuxt.js part#6 Create Store in Vuex, Request data in Vuex, Data centralized"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id64,883,081
net_rshares0
@portugalcoin ·
Thank you for your contribution.

- Your tutorial is very well explained and easy to understand. Good job!!!

Your contribution has been evaluated according to [Utopian policies and guidelines](https://join.utopian.io/guidelines), as well as a predefined set of questions pertaining to the category.

To view those questions and the relevant answers related to your post, [click here](https://review.utopian.io/result/8/11111313).

---- 
Need help? Write a ticket on https://support.utopian.io/. 
Chat with us on [Discord](https://discord.gg/uTyJkNm). 
[[utopian-moderator]](https://join.utopian.io/)
πŸ‘  ,
properties (23)
authorportugalcoin
permlinkre-duskiharahap-universal-vue-js-application-with-nuxt-js-part-6-create-store-in-vuex-request-data-in-vuex-data-centralized-20180716t213234158z
categoryutopian-io
json_metadata{"tags":["utopian-io"],"links":["https://join.utopian.io/guidelines","https://review.utopian.io/result/8/11111313","https://support.utopian.io/","https://discord.gg/uTyJkNm","https://join.utopian.io/"],"app":"steemit/0.1"}
created2018-07-16 21:32:33
last_update2018-07-16 21:32:33
depth1
children0
last_payout2018-07-23 21:32:33
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length600
author_reputation598,828,312,571,988
root_title"Universal Vue.js application with Nuxt.js part#6 Create Store in Vuex, Request data in Vuex, Data centralized"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id64,916,576
net_rshares6,292,940,780
author_curate_reward""
vote details (2)
@utopian-io ·
Hey @duski.harahap
**Thanks for contributing on Utopian**.
We’re already looking forward to your next contribution!

**Want to chat? Join us on Discord https://discord.gg/h52nFrV.**

<a href='https://v2.steemconnect.com/sign/account-witness-vote?witness=utopian-io&approve=1'>Vote for Utopian Witness!</a>
properties (22)
authorutopian-io
permlinkre-universal-vue-js-application-with-nuxt-js-part-6-create-store-in-vuex-request-data-in-vuex-data-centralized-20180717t151509z
categoryutopian-io
json_metadata"{"app": "beem/0.19.42"}"
created2018-07-17 15:15:09
last_update2018-07-17 15:15:09
depth1
children0
last_payout2018-07-24 15:15:09
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length305
author_reputation152,955,367,999,756
root_title"Universal Vue.js application with Nuxt.js part#6 Create Store in Vuex, Request data in Vuex, Data centralized"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id65,003,429
net_rshares0