Despite using Vue and Vuex with Axios asynchronously, the getters are still returning an empty array

I am encountering an issue with getters that are returning the initial state (an empty array).

In my component, I have a method called created that sets the axios call result into the state.

created() {this.$store.dispatch("SET_STORIES");},

I am using mapGetters in the computed section:

  computed: {
    ...mapGetters(["GET_STORIES"])
  },

There is also a method to get the state:

  methods: {
    stories() {
      return this.$store.getters.GET_STORIES;
    }
  }

The mounted() hook is displaying an empty array:

  mounted() {
    console.log("stories", this.$store.getters.GET_STORIES);
  },

store.js

import Vue from "vue";
import Vuex from "vuex";
import axios from "axios";
import VueAxios from "vue-axios";
import chunk from "lodash/chunk";
Vue.use(Vuex, VueAxios, axios);

export default new Vuex.Store({
  state: {
    stories: [],
    twoChunkStories: []
  },
  getters: {
    GET_STORIES: state => {
      return state.stories;
    }
  },
  mutations: {
    SET_STORIES(state, stories) {
      state.stories = stories;
    },
    SET_CHUNKED_STORIES(state, stories) {
      state.twoChunkStories= stories;
    },
  },
  actions: {
    SET_STORIES: async ({ commit }) => {
      const options = {
        headers: {
          "Content-Type": "application/json"
        }
      };
      let { data } = await axios.get(
        "https://api.example.com/get.json",
        options
      );
      if (data.meta.code === 200) {
        let storiesArray = data.data.stories;
        let chunkSize = 2;
        commit("SET_STORIES", storiesArray);
        let chunkedArray = chunk(storiesArray, chunkSize);
        commit("SET_CHUNKED_STORIES", chunkedArray);
      }
    }
  }
});

I am trying to figure out how to make an asynchronous axios call to set the state onload in the earliest possible lifecycle hook (which I thought was created()) and be ready to be accessed on mounted. There seems to be an issue with how I am handling the asynchronous operation over the getters, but I'm unsure of what exactly it is.

Answer №1

Your component is missing a call to the action method SET_STORIES, which means that the stories in your store will not be updated. To fix this, you should include a call to the action in your Vue component like so:

mounted() {
 this.$store.actions.SET_STORIES
}

Additionally, it might be beneficial to rethink your approach here, as you cannot predict how long it will take to fetch the stories data from the server.

You can create a variable called isDataLoaded in your component and set it to false initially. Then, conditionally render your list based on this variable:


<div v-if="!isDataLoaded">
  Loading ...
</div>

<div v-if="isDataLoaded">
  ... your list goes here ...
</div>

In your mounted() method, make sure to update isDataLoaded after calling the action to ensure that your list displays correctly:

async mounted() {
 await this.$store.actions.SET_STORIES
 this.isDataLoaded = true
}

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

Calculating the sum of values in a GridView using ASP.NET

I have an ASP.NET Web Application where I am utilizing a BulkEditGridView to create an order form. This GridView allows users to edit all rows simultaneously. Within the grid, there is a column that calculates the total cost for each item (cost x quantit ...

What is the reason behind VueJS animations only functioning in a single direction?

I'm completely baffled by this issue. It seems that Vue3 is able to apply the move animation class correctly for a <transition-group/> when there is a list of items, but this only happens if the list is moved forward. I've created a CodePen ...

Limiting the usage of a command in Discord.js to one user at a time, rather than all users

I'm in the process of developing a discord.js bot and I need to implement a cooldown for a specific command. After searching several tutorials online, I found that most of them apply the cooldown to all commands (meaning all users have to wait a set ...

Unable to deploy a node.js package via a jenkins job

I'm looking to set up a Jenkins job that will publish a package to npmjs.com. The source code for the package is located in a GitHub repository. While I am able to successfully publish the package from my personal computer by running 'npm publis ...

"Exploring the depths of PHP: Generating a JSON string from an array

I am trying to work with PHP code in an Object-Oriented manner and the values I am getting are objects. However, I need to convert these O.O.P objects into JSON data for use by JavaScript. So, I converted my objects into arrays on the PHP end, but when I t ...

What's the best way to mount a file on a field?

Can you assist in resolving this issue by utilizing a form on JSFiddle? If a user fills out the following fields: name, email, phone, message The data should be output to the console. However, if a user adds a file to the field attachment No output ...

Challenges with Scaling HTML5 Video onto Canvas

Attempting to extract a frame from an html5 video to generate a thumbnail, but encountering peculiar outcomes when the image is rendered onto canvas. The issue lies in the fact that the canvas displays only a greatly magnified portion of the video! Refer ...

The data type 'string[]' cannot be assigned to the data type 'listData[]'

I'm currently developing a flexible component that allows the list view to be utilized by different components. However, the challenge arises from the fact that each component has a different data format. In my project, I'm unable to use type any ...

Add an element to the input field

Two input buttons are available for users to upload files. <input type="file" id="fileUpload" name="files" multiple><br/> <div id="selectedFiles"></div> The selected files will be appende ...

VueJS encountered an error during rendering: TypeError - Unable to access the 'PRICE' property of undefined

My goal is to calculate the total bill, which is the sum of all product prices multiplied by their respective usage values, using the customerProduct data object. Once calculated, I want to display the bill amount. To achieve this, I have a computed method ...

Having trouble loading environment variables in NextJS on Heroku?

I am currently utilizing NextJS and deploying my application on Heroku. When the page initially loads, I am able to retrieve data through getInitialProps without any issues. However, when trying to access this data in a regular function, I encounter an er ...

Passing a JSON object as a parameter in a dynamically created element's click event using JavaScript/AngularJS

How to pass a JSON object as a parameter in the click event of a dynamically created element using JavaScript and AngularJS? var _dataObj = "{"sor_SourcingAgentId":1,"sor_Name":"xx"}" var _dynHtml= '<input type="button" ng-click="fnSelectcustom ...

Display or conceal component based on specific URL in React.js navigation bar

Hey there, I'm facing an issue with hiding certain links in the navbar when users visit specific pages. For instance, on the Landing page, I want to hide the Orders and Basket links and only show the Login link. I'm having trouble figuring out ho ...

I'm puzzled as to why my recursive function is repeatedly calling itself without meeting the necessary logical condition. Can anyone provide guidance on

As I delve into a basic recursion, I am observing an interesting phenomenon where the logic governing the recursion is activated even when a false parameter is present in the return statement for the ternary rule. This particular recursive function perfor ...

How can we trigger the Skill bar effect upon scrolling to the section?

I have created a stunning Skill Bar that is functioning perfectly. However, I am looking to enhance the experience by having the skill bar effect trigger only when I scroll to that specific section. For example, as I navigate from the introduction section ...

Using Regular Expressions for Validation

As a designer trying to set up a payment page without strong developer skills, I've hit some roadblocks. The payment company gave me guidance that involved using regular expressions for validating the 'AMOUNT' field, but my attempts to modif ...

Angular 4: Unhandled error occurred: TypeError - X does not exist as a constructor

I am currently developing a project in Angular 4, and I encountered an error while running the application. The specific error message is as follows - ERROR Error: Uncaught (in promise): TypeError: index_1.EmployeeBase is not a constructor TypeError: in ...

Ways to maneuver the vehicle by using the left or right key inputs

I am a beginner with canvas and game development. I am currently working on a project where a car moves in a straight line, but I want to add functionality for the car to turn anti-clockwise when the left key is pressed, and clockwise when the right key is ...

What steps can be taken to confirm the accuracy of input before sending it

Having trouble with validating input before submitting? Every time I run submit(), something seems to be going wrong :( const [value, setValue] = React.useState(""); const [error, setError] = React.useState(""); const validate = () => { value.length ...

Learn the steps to activate on-page editing feature!

Is there a way to make a section of a webpage editable when a button is clicked? (e.g. edit & view on the same page) For instance, imagine you could click "edit" on this very page (the one you are currently reading), and the title and content become edita ...