How to call API from Axios in Vuex store. 💾

ljnce

Luca

Posted on August 12, 2020

How to call API from Axios in Vuex store. 💾

Hi Dev Friends! 🤠

In this.tutorial i will show you in which mode you can use Axios with Vuex, and call it on you file.Vue.

STEP ONE:

First of all you can add Vuex on your project:

0️⃣) I suggest you to add this, during the installation of Vue.cli, via "manual installation":

vue create project
Enter fullscreen mode Exit fullscreen mode

Alt Text

Alt Text

After this you need to install Axios:

npm install --save axios vue-axios
Enter fullscreen mode Exit fullscreen mode

Import Axios on your store -> index.js

import axios from 'axios'
import VueAxios from 'vue-axios'

Vue.use(Vuex)
Vue.use(VueAxios, axios)
Enter fullscreen mode Exit fullscreen mode

STEP TWO:

And now let's create👩‍💻:

1️⃣)Determinate your items.
export default new Vuex.Store({
  state: {
        items: [],
    },
Enter fullscreen mode Exit fullscreen mode
2️⃣)Your getter:
    getters: {
        items: state => {
            return state.items;
        }
    },
Enter fullscreen mode Exit fullscreen mode
3️⃣)Mutation of your items
    mutations: {
        SET_Item (state, items) {
            state.items = items
        }
    },
Enter fullscreen mode Exit fullscreen mode
4️⃣)Action for call your API on you file.Vue
    actions: {
        loadItems ({ commit }) {
            axios
                .get('Your API link', {
                    headers: {
                        'Ocp-Apim-Subscription-Key': 'your key',
                    }
                })
                .then(response => response.data)
                .then(items => {
                    console.log(items);
                commit('SET_Items', items)
            })
        }
    },
});
Enter fullscreen mode Exit fullscreen mode

STEP THREE:

Now it's time to call your "items" on your file.Vue:

1️⃣)Import you mapState from vex:
   <script>

import { mapState } from 'vuex';

Enter fullscreen mode Exit fullscreen mode
2️⃣) With mounted you can stamp your API, and use "dispatch" method to call the "action" (the difference with mutations is you can use "mounted" method).

    mounted () {
        this.$store.dispatch('loadItems')
    },
Enter fullscreen mode Exit fullscreen mode
3️⃣)Add mapState on your computed:

     computed: mapState([
        'items'
    ]),

</script>
Enter fullscreen mode Exit fullscreen mode
4️⃣)Compile you template with your API.
<template>
  <div class="my-items">
    <div v-for="item in items" :key="items.id">
       // Your v-for...
    </div>
 </div>
</template>
Enter fullscreen mode Exit fullscreen mode

Hope I help you!
🙋‍♂️

💖 💪 🙅 🚩
ljnce
Luca

Posted on August 12, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related