Vuex: The getter is unable to retrieve data from an external API

When attempting to retrieve data from an external API and display it in my component, I am encountering an issue where the returned result is an empty array despite the fact that there is data present in the API. Here is the relevant code snippet from my module:

import axios from 'axios';

const state = {
    countries = []
}

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

const actions = {
    //Fetch all 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>

Answer №1

Make sure to dispatch the action properly by running it within 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>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Security measures for interacting with REST API by both frontend application and secondary backend service

I currently have a REST API backend service A that is being utilized by two other services: B service, which is a web app running in a browser (on a separate node server) C service, which is also a backend service (running on a separate server) Initiall ...

The prop "chartData" was not valid: expected an Object but received Null in vue.js

I encountered an error while running this code: [Vue warn]: Invalid prop: type check failed for prop "chartData". Expected Object, got Null Here is how I am implementing the vue-chartjs component: <div class=""> <DoughnutChart :chartData= ...

adjusting the font color based on the currently selected tab

After seeking help for my previous question on Unable to add a background colour to the button in navigation I have successfully resolved that issue and continued working, but now I am facing a new challenge. I need to change the font color of the navigat ...

Ajax script failing to run

I'm currently developing a new social networking site that includes a feature for creating groups. Most of my code is functioning flawlessly, except for this small section that handles approving or declining pending members. The following PHP code sni ...

I am encountering an issue with the appendChild() method when trying to create a new element using createElement("ul")

I am facing an issue with creating a UL and LI elements beneath the P tag. Would appreciate it if someone could review my code below. The javascript is showing the following error message: Uncaught TypeError: thisIsQuizContainer.appendChild is not a fu ...

Symfony2 and asynchronous JavaScript and XML (AJAX)

Is there a way to perform asynchronous actions in Symfony2 without having to refresh the page? I haven't been able to find any information about this in the official "Book" or "Cookbook". (The only mention I came across was 2 sentences about hinclude. ...

Access the OpenWeatherMap API to retrieve the weather forecast for a single time slot within a 5-day period

Utilizing the openweathermap api, I am retrieving a 5-day/3-hour forecast here. The API call provides multiple results for each day with data available every 3 hours. For the full JSON response, you can access it here. Please note that the API key is only ...

Executing JQuery and Ajax calls within a loop

Can I dynamically change the variable in ("xxxxx").html(data) inside a for loop? I've been struggling to figure this out. My goal is to populate an HTML table with JSONP data from multiple ajax calls within a loop, where the URL changes each time. Wh ...

Issue encountered while updating database using form in vue.js + MongoDB

I am encountering an issue with the Update functionality on my CRUD application. Below is the form that is utilized for both creating and updating: <template> <form @submit.prevent="submitForm"> ... </form> </templat ...

What is the process for assigning a PHP function's return value to a JavaScript variable?

Is there a way to retrieve a value from a PHP function and assign it to a JavaScript variable? As shown in the following example: PHP: // Destination folder for downloaded files $date = date('m.d.y'); mkdir("uploads/" . $date, 0777, true); $ ...

Using Redux to populate initial input values in React

Here's the situation - I have an input field where users can enter their email address. When they click 'save,' this email is stored in the database. The challenge I'm facing is that when the page is refreshed, I want the input field t ...

choose multiple elements from an array simultaneously

Looking for help with a basic Array question and seeking the most effective solution. The scenario involves having an array: var pathArr = [element1, element2, element3, element4, element5, element6] If I want to select multiple elements from this array ...

Employing a while loop within the context of a Promise

I am currently working on a user list and checking users with specific details. I'm utilizing sequelize js with express for this task. My query is whether it is possible to use a while loop in this manner to search and save data in the database. Any a ...

Develop a slider feature based on radio button selection

I am currently working with radio buttons for ticket selection. <div> <input type="radio" name="ticket" value="Standard"> Standard <input type="radio" name="ticket" value="Express"> Express <input type="radio" name="ticket" value= ...

Event handlers for the Swiper Vue component seem to be malfunctioning within NuxtJS

I'm currently implementing Swiper.js in my Nuxt project using the default code provided by the documentation. However, I'm encountering an issue when trying to log the swiper instance as it seems to not be working properly. In the console, the fo ...

Steps for executing the function in the specifications - Protractor

My script is written within the following module: var customSearch = function () { this.clickSearch = function (value) { element(by.id('searchbutton')).click(); }; this.waitElementFound = function (value) { var EC = protractor.Ex ...

When submitting a form with the jQueryForm plugin, take action on the form by selecting it with `$(this)`

I have a situation where I have multiple forms on one page and am utilizing the jQuery Form plugin to manage them without having to reload the entire page. The issue arises when I need some sort of visual feedback to indicate whether the form submission wa ...

The error message "Quasar VUE_PROD_HYDRATION_MISMATCH_DETAILS has not been declared" is

Currently using quasar in conjunction with Vite. Upon installation of Quasar via yarn create quasar, a warning message appears in the console: __VUE_PROD_HYDRATION_MISMATCH_DETAILS__ is not explicitly defined. You are running the esm-bundler build of Vue, ...

What strategies can be employed to enhance the natural movement of dots on my HTML canvas?

Check out my code pen here I'm looking for feedback on how to make the movement of the canvas dots more fluid and liquid-like. I've experimented with restricting the direction for a certain number of renders (draw()), which has shown some impro ...

Utilizing shared state across multiple files in ReactJS

Learning React has been a challenge for me and I'm struggling to grasp it. How can I access this.state.planet in the newMove() function? I keep getting an error message - Uncaught TypeError: Cannot read property 'state' of undefined. Be ...