user12192123
user12192123

Reputation:

Vuex: Getter is not fetching data from external API

I'm trying to fetch data from an external API and display the data in my component but it is returning an empty array when I actually have data in my API. Inside my module I have the following:

import axios from 'axios';

const state = {
    countries = []
}

const getters = {
    allCountries: (state) => state.countries;
}

const actions = {
    //Fecth all the countries from the API
  async fetchCountries({ commit }) {
    const response = await axios.get('URL');
    commit('setCountries', response.data);
  },
}

const mutations = {
    setCountries: (state, countries) => (state.countries = countries),
}

export default {
  state,
  getters,
  actions,
  mutations,
};

Component:

<template>
    <div v-for="country in allCountries" :key="country.id">
       <small>{{country.name}}</small>
    </div>
</template>
<script>
import { mapGetters} from 'vuex';

export default{
    name: 'CompCountry',
    computed: mapGetters(['allCountries'])
}
</script>

Upvotes: 0

Views: 493

Answers (1)

Boussadjra Brahim
Boussadjra Brahim

Reputation: 1

You're missing to dispatch the action, to do that you should run it in a life cycle hook like mounted :

<template>
    <div v-for="country in allCountries" :key="country.id">
       <small>{{country.name}}</small>
    </div>
</template>
<script>
import { mapGetters} from 'vuex';

export default{
    name: 'CompCountry',
    computed:{ ...mapGetters(['allCountries']},
   mounted(){
     this.$store.dispatch('fetchCountries')
   }
}
</script>

Upvotes: 1

Related Questions