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

Using Vuex axios get request, we will see how we can dispatch an action to get the data from the server and then update the state of our application and display that data into the Vue component. I use Vue 3, Vuex for state management, and Axios for the client-side network request library to send an HTTP request. In this example,  So let us start.

Vuex Axios example overview

  1. Scaffolding a Vue.js project with Vue CLI and installing required dependencies.
  2. Setting up the project structure and SCSS.
  3. Setting up vue-router.
  4. Setting up the REST API.
  5. Setting up the Vuex store.

We start our project by installing the Vue.js using the Vue cli.

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, then try the command in administrator mode.

Now, create a project using the following command.

vue create vuexapi

Now, 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.

So let’s create a static JSON file, and then we serve that file as an API via 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 in that folder, create one file called db.json. 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"
	}
     ]
}

Now, go into your terminal and type the following command to start a JSON server.

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

Now, we have a server running that 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, and 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 that will 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 very 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 need to create an action to fetch the data from an API. 

So, 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 commit as an argument and then call the mutation using the commit function.

So, 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
    }
  }
})

So 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.

Now, 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>

So, 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 set our Vue.js application state’s coins array to the fetched coins.

Now, that coins we map here inside computed properties.

Finally, loop through all the coins and display it as a table format.

Vuex Axios Get Request Tutorial With Example

 

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

Saving all your state variables, getters, actions, and mutations in one single file will quickly become cumbersome once you start working on medium to large-sized real-world applications.

Let’s see how we can organize our store into multiple files as modules.

That’s it for this tutorial. Thanks for taking it.

See Also

Vue axios example

Vue Laravel CRUD

Vue router example

Vue event handling

Vue datatable example

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.