Vuex Axios: How to Send Vuex Axios GET Request in Vue

Here are the steps to send an axios get request using vuex in Vue.js.

Step 1: Install Vue using Vue cli.

Type the following command in your terminal.

npm install -g @vue/cli

# or

yarn global add @vue/cli

If you find any installation error, try the administrator mode command.

Create a project using the following command.

vue create vuexapi

Go into that project.

cd vuexapi

Open the project in your favorite editor.

code .

Step 2: Install Vuex, Axios, and vue-axios libraries.

Go to the terminal and install the vuex, axios, and a vue-axios library using the following command.

npm install vuex axios vue-axios --save

Install Bootstrap 4 as well.

npm install bootstrap --save

Import this file inside the App.vue file.

<template>
  <div id="app">
    <HelloWorld />
  </div>
</template>

<script>
import HelloWorld from './components/HelloWorld.vue'
import '../node_modules/bootstrap/dist/css/bootstrap.min.css';

export default {
  name: 'app',
  components: {
    HelloWorld
  }
}
</script>

Step 3: Create a JSON server to serve the data.

In a real web application, we have data coming from an API.

Create a static JSON file, and then we serve that file as an API via the json-server package. So let us install that library first.

yarn global add json-server

# or

npm install -g json-server

Now we need to create a folder inside the src directory called data and create one file called db.json in that folder. Let us add the following data inside a db.json file.

{
  "results": [
	{
	   "id": "1",
	   "name": "BTC",
	   "price": "1000"
	},
	{
	    "id": "2",
	    "name": "LTC",
	    "price": "150"
	},
	{
	    "id": "3",
	    "name": "Ethereum",
	    "price": "800" 
	},
	{
	    "id": "4",
	    "name": "BCH",
	    "price": "1500"
	}
     ]
}

Enter your terminal and type the following command to start a JSON server.

json-server --watch src/data/db.json --port 4000

Our server can feed the data to our React Bootstrap Application.

Our JSON server is started at port: 4000, and the URL is http://localhost:4000/results.

Step 4: Create a vuex store.

Inside the src folder, create one folder called a store; inside that folder, create one file called store.js.

Write the following code inside a store.js file.

// store.js

import Vue from 'vue'
import Vuex from 'vuex'
import axios from 'axios'
import VueAxios from 'vue-axios'

Vue.use(Vuex)
Vue.use(VueAxios, axios)

export default new Vuex.Store({
  state: {
     coins: []
  },
  actions: {
    
  },
  mutations: {
    
  }
})

We are merely displaying the coins. So our primary state object contains a coins array.

Our store contains state, actions, and mutations.

The state contains our whole vue application state.

 The actions contain the function to call our JSON Server via Axios and get the response.

The only way to change the state in a Vuex store is by committing a mutation.

Vuex mutations are similar to events: each mutation has a string type and a handler. The handler function is where we perform actual state modifications, and it will receive the state as the first argument.

Step 5: Create an action.

Inside the store.js file, we must create an action to fetch the data from an API. 

We can write the store function like this.

// store.js

import Vue from 'vue'
import Vuex from 'vuex'
import axios from 'axios'
import VueAxios from 'vue-axios'

Vue.use(Vuex)
Vue.use(VueAxios, axios)

export default new Vuex.Store({
	state: {
    coins: []
  },
  actions: {
    loadCoins ({ commit }) {
      axios
        .get('http://localhost:4000/results')
        .then(r => r.data)
        .then(coins => {
        console.log(coins)
        })
    }
  },
  mutations: {
    
    }
  }
})

Inside actions, we have created one function called loadCoins. This function will take the commit as an argument and then call the mutation using the commit function.

We need to write mutations as well. Our final store.js file looks like this.

// store.js

import Vue from 'vue'
import Vuex from 'vuex'
import axios from 'axios'
import VueAxios from 'vue-axios'

Vue.use(Vuex)
Vue.use(VueAxios, axios)

export default new Vuex.Store({
	state: {
    coins: []
  },
  actions: {
    loadCoins ({ commit }) {
      axios
        .get('http://localhost:4000/results')
        .then(r => r.data)
        .then(coins => {
        commit('SET_COINS', coins)
        })
    }
  },
  mutations: {
    SET_COINS (state, coins) {
      state.coins = coins
    }
  }
})

After the coins are fetched, we can commit a mutation,

In our case, the mutation is SET_COINS. So we call that mutation function with an argument of coins. 

Set the coins state with our fetched coins.

We can use these coins to display the data.

Step 6: Display the coins in table format.

In the default Vue.js project, we get the HelloWorld.vue file. So write the following code inside the HelloWorld.vue file.

<template>
  <div class="container">
    <table class="table table-striped">
      <thead>
        <tr>
          <th>ID</th>
          <th>Name</th>
          <th>Price</th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="coin in coins" :key="coin.id">
          <td>{{ coin.id }}</td>
          <td>{{ coin.name }}</td>
          <td>{{ coin.price }}</td>
        </tr>
      </tbody>
    </table>
  </div>
</template>

<script>
import { mapState } from 'vuex'
export default {
  name: 'HelloWorld',
  mounted () {
    this.$store.dispatch('loadCoins')
  },
  computed: mapState([
    'coins'
  ])
}

</script>

What I have done is when the component is mounted, we call the store’s action.

In our case, that action is loadCoins.

So, it will fetch the coins and commit the mutation called SET_COINS.

This mutation sets our Vue.js application state’s coins array to the fetched coins.

Now, the coins we map here are inside computed properties.

Finally, loop through all the coins and display them in a table format.

Vuex Axios Get Request Tutorial With Example

 

So this is how you can work with Vue.js, Vuex, and axios library.

That’s it!

5 thoughts on “Vuex Axios: How to Send Vuex Axios GET Request in Vue”

  1. Your tutorials are great. I don’t know whether you have a youtube channel, but in video form it would get you more followers.

    Reply
  2. Did I miss where you added the Store to main.js? I looked through a couple times and didn’t see it. If you choose to install vuex in the CLI it adds if for you, but when you add after the initial creation you have to import the store manually.

    Reply
  3. if you came across the problem with state, change main.js to look like this:

    import Vue from ‘vue’
    import App from ‘./App.vue’
    import store from ‘./store/store’
    Vue.config.productionTip = false

    new Vue({
    store,
    render: h => h(App)
    }).$mount(‘#app’)

    Reply

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.