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

The Angular error TS2531 occurs when attempting to call scrollIntoView on an object that may be null

In my current Angular project, I am attempting to implement a scroll view using ViewChild by id. This is the method I have written: ngOnInit() { setTimeout(() => { if (this.router.url.includes('contact')) { ...

Next.js is like Gatsby but with the power of GraphQL

I'm curious if it's possible to set up GraphQL in Next.js similar to how it's done in Gatsby, allowing me to query pages and retrieve data from them. Are there any plugins available for Next.js that work like Gatsby-file-source and gatsby-ma ...

What is the correct method of implementing the "OnChange" event to a WooCommerce select element?

My task is to include the onchange="myFunction()" in the select menu below. However, because the select menu is part of woocommerce, I want to ensure that the onchange="myFunction()" remains intact even after updating my theme. How can I achieve this goal ...

What steps can I take to avoid encountering this endless loop?

When passing foo in the arguments of useEffect to use existing array values, it causes an infinite loop because setting new values triggers the f() function again. How can this be resolved? An example of imaginary code is: const [foo, setFoo] = useState&l ...

Is there a constraint on JSON data?

Is there a limit to the amount of data that JSON with AJAX can handle in outgoing and returning parameters? I am trying to send and receive a file with 10,000 lines as a string from the server. How can I accomplish this task? Can a single parameter manage ...

How can I incorporate sass abstracts into all my Vue components when using Vite as a build tool?

I am currently tackling a project that utilizes vue3, vue-router, vuex, and sass with vite as the chosen build tool. In my previous projects with vue-cli, I utilized a vue.config.js file to automatically import sass abstracts into all components using we ...

retrieving a URL with the help of $.getJSON and effectively parsing its contents

I seem to be struggling with a coding issue and I can't quite figure out what's wrong. My code fetches a URL that returns JSON, but the function is not returning the expected string: function getit() { var ws_url = 'example.com/test.js&ap ...

Vue 3 Composable console error: Unable to access properties of undefined (specifically 'isError') due to TypeError

I recently developed a Vue 3 / TypeScript Composable for uploading images to Firebase storage. The code snippet below illustrates the structure of the ImageUpload interface: interface ImageUpload { uploadTask?: UploadTask; downloadURL?: string; progr ...

What is the approach for for loops to handle non-iterable streams in JavaScript?

In the realm of node programming, we have the ability to generate a read stream for a file by utilizing createReadStream. Following this, we can leverage readline.createInterface to create a new stream that emits data line by line. const fileStream = fs.cr ...

An issue has occurred with NPM CI where the bindings are not available from watchpack-chokidar2:fsevents

After executing npm ci on GitHub Actions, I encountered the following error: Run npm ci npm ERR! bindings not accessible from watchpack-chokidar2:fsevents npm ERR! A complete log of this run can be found in: npm ERR! /home/runner/.npm/_logs/2021-09-17 ...

How can I style the empty text in an ExtJS grid using CSS?

Is there a specific CSS class for a grid's emptyText? After inspecting the element with Firebug, all I found was: <div id="gridview-1021" class="x-component x-grid-view x-fit-item x-component-default x-unselectable" role="presentation" tabindex=" ...

What steps do I need to take to transform this click event function into one that is triggered automatically upon the div loading?

In order to automatically load content into a div using innerHTML, the PHP file must be retrieved and the div updated with its content. Within this div is another one labeled "tweet" which displays actual tweets based on a specific hashtag provided through ...

Having trouble modifying a value in a form and submitting it to the following jsp page

I'm encountering an issue with changing the value in a hidden input element before submitting data to another JSP file (db.jsp) for processing. The value should be different depending on which button is clicked, but it always remains as the default va ...

What is the best way to pass an array through router navigate function?

I've searched for a solution in other questions, but nothing has helped me... My goal is to redirect to a URL like this: this.router.navigateByUrl('/products'); I want to pass an array and retrieve it in the component with the active link ...

JQuery Mobile Navigation with Bootstrap 3 Sidebar on the Go

While using RoR, I encountered a baffling issue. I have created a new navbar with a sidebar that only displays on mobile and not on desktop. The Turbolink is functioning properly. <%= javascript_include_tag 'application', 'data-turboli ...

Mastering the management of various events within React Material UI components

I am working with a Material UI Switch Component and need to detect click events on it. In certain situations, I want to prevent the change event from triggering. What is the most effective way to achieve this? While I have previously used event.preventD ...

The variable req.body.username is not defined in the context of JavaScript

I am completely new to JS, Angular.js and node.js. I am currently working on a login-register project but facing a minor issue. Below is my code: login.ctrl.js: var app = angular.module('login-register', []); app.factory('UserLog', ...

Does every controller page need to verify the Login Function?

In my PHP pages, I have implemented the MVC Pattern by creating a controller page for each view page to interact with the Model page. However, I have only checked user login at the top of every view page and not in the controller page. This leaves a potent ...

Tips on sending a form to the server with ajax technology

I'm struggling with sending a button id to my server through ajax in order to submit a form without having to constantly reload the page every time I click on a button. Unfortunately, it's not working as expected and I can't figure out why. ...

Unable to define an object within the *ngFor loop in Angular

In order to iterate through custom controls, I am using the following code. These controls require certain information such as index and position in the structure, so I am passing a config object to keep everything organized. <div *ngFor="let thing of ...