The VueJS application's Vuex Getter appears to display as an empty array, yet when utilizing console.log, it reveals itself as an object containing all the corresponding values

Here's the method I'm using, it's pretty straightforward.

DailyCountTest: function (){
  this.$store.dispatch("DailyCountAction")
  let NewPatientTest = this.$store.getters.NewPatientCountGET
  console.log(NewPatientTest)

}

The getter retrieves data from a simple action that accesses a django backend API.

I'm trying to create some charts with the data, so I need to store them in variables. The issue is that I can't seem to access these variables.

Here's what the console displays

And here it is expanded.

You can see the contents, but there are also empty brackets. Does anyone know how I can access those values? I've tried various map.(Object) methods but haven't had any success.

Any tips on how to manipulate this array and extract the contents?

Thank you!

Below is the Vuex path for the API data

Action:

    DailyCountAction ({ commit }) {
      axios({
          method: "get",
          url: "http://127.0.0.1:8000/MonthlyCountByDay/",
          auth: {
            username: "test",
            password: "test"
          }
        }).then(response => {
          commit('DailyCountMutation', response.data)
          })
  },

Mutation:

    DailyCountMutation(state, DailyCount) {
      const NewPatientMap = new Map(Object.entries(DailyCount));

      NewPatientMap.forEach((value, key) => {
        var NewPatientCycle = value['Current_Cycle_Date']
        state.DailyCount.push(NewPatientCycle)
      });
    }

Getter:

  NewPatientCountGET : state => {
    return state.DailyCount
  }

State:

    DailyCount: []

Answer №1

After reviewing your issue, I noticed a specific description that stood out to me:

The getter gets that data from a simple action that calls a django backend API

Based on this information, it seems like there could be an asynchronous action causing a potential race condition. Can you provide a sample of the getter function to help confirm my suspicion?

If the getter is indeed reliant on an action to populate its contents, you might consider implementing something similar to the following approach:

DailyCountTest: async () => {
  await this.$store.dispatch('DailyCountAction')
  await this.$store.dispatch('ActionThatPopulatesNewPatientCount')
  let NewPatientTest = this.$store.getters.NewPatientCountGET
  // ... perform necessary operations with resulting array
}

Answer №2

If you're looking to optimize your code, consider using a computer property as well. One approach is importing mapGetters:

import { mapGetters } from 'vuex'

Afterwards, in the computed properties section:

computed: {
    ...mapGetters(['NewPatientCountGET'])
}

This allows you to access and utilize NewPatientCountGET, which will automatically update whenever there's a change in its corresponding store value (for instance, after receiving new data from an API call).

I hope this explanation clarifies things for you!

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

Creating a unique seal, badge, or widget in Django is a fun and rewarding project

Here are some examples of what I want to accomplish: View the gif showcasing the function Visit https://sectigo.com/trust-seal Check out another gif demonstrating the function Explore https://www.carandtruckremotes.com/ Don't miss this gif showin ...

Selecting the appropriate color code based on a specified value

If the value of zoneTempDiff1 falls below 1.5, consider using temp: 1 color. If it exceeds 1.5, opt for temp: 2 color. The same logic applies to all different values such as -1, -2, 0, 1, 2, 3, 4, or 5, each corresponding to a specific color code. In cas ...

Steps to display a single entry in a Laravel/Vue implementation

My goal is to combine Laravel with Vue and eventually Nuxt in order to incorporate dynamic page transitions similar to the ones showcased on into my websites. I recently followed a tutorial on using Vue with Laravel at https://scotch.io/tutorials/build-a ...

What is the process of using JavaScript code to read a text file?

Trying to use Google Charts while reading data from a text file. The code in JS is written for this purpose: function readTextFile(file){ var rawFile = new XMLHttpRequest(); rawFile.open("GET", file, false); // using synchronous call var allTe ...

Tips for showing data from an hour ago in Angular

Here is the code snippet provided: data = [ { 'name' : 'sample' 'date' : '2020-02-18 13:50:01' }, { 'name' : 'sample' 'date' : '2020-02- ...

Having troubles with the xml2json jQuery plugin's functionality?

I've implemented the jQuery XML to JSON Plugin by Fyneworks.com. Any idea why my code isn't functioning as expected? index.html <!DOCTYPE html> <html> <head> <script src="build/jquery.xml2json.js"></script> <sc ...

Is there a way to automatically populate an AngularJS input field?

Attempting to automate filling out a website using JavaScript. The script below: document.getElementsByClassName('form-control')[1].value = "MYNAME"; The input text changes, but upon clicking the submit button it displays as empty. Any as ...

How to conditionally disable the @click event on an image element in Vue.js

I am presenting the code snippet below: <image id="wheel-bg" class="wheel-bg" :x="-width/2" :y="-height/2" href="images/wheel-bg.png" :width="width" :height="he ...

Transform the javascript ES6 class into a functional programming approach

I am interested in converting my reactjs class to a functional programming approach rather than using OOP. Can anyone provide guidance on how to achieve this? Please refer to my code snippet below. import * as h from './hydraulic'; const vertic ...

Utilizing Typescript for parsing large JSON files

I have encountered an issue while trying to parse/process a large 25 MB JSON file using Typescript. It seems that the code I have written is taking too long (and sometimes even timing out). I am not sure why this is happening or if there is a more efficien ...

How can I trigger the modal if emitting "go-modal" at another instance does not work?

I have implemented the standard vuetifyjs/dialogs on my page without any server-side scripts. The layout of the components on the page is structured as follows: <div id="main"> ... <v-expansion-panel>...<!-- v-for... --> <v ...

Error: An uncaught exception occurred when trying to access a seekable HTML5 audio element, resulting in an IndexSize

While trying to utilize the HTML5 API along with SoundManager2, I encountered an issue. My goal was to determine the duration of a song in order to create a progress bar that would update as the song played. However, every time I attempted to retrieve the ...

Passing a method as a parameter type

As I delve into learning JavaScript from Objective-C, I find myself pondering whether it is possible to have a method with parameter types in Objective-C. Let's take the example of the findIndex() JavaScript function that identifies and returns the in ...

Functionality of jQuery Mobile Page

$(document).on("pageshow", "#mappage", function (event) { $("#doldur").append("<li> <label onclick='getBina(" + featuressokak[f].attributes.SOKAKID + ");'>" ...

Cypress testing with Vue: a guide to mocking API calls using actions in Vue

Could someone help me test an action involving an API call? This is the action in my Vuex store: The file containing actions in my store is 'ex.js', and it includes exActions.js export const exActions = { getExFromApi({ commit, rootGetters ...

Unable to retrieve element using getElementById within the beforeDestroy lifecycle hook of VueJS

When I utilize document.getElementById within the beforeDestroy lifecycle, it returns null. However, if I use ref, I am able to retrieve the element successfully. What exactly is the difference between these two methods? Why is it that document.getElemen ...

Issue with model not displaying after material added in OBLLoader + MTLLoader

After loading a material using MTLLoader and applying it to my model loaded with OBJLoader, the model itself mysteriously disappears. MTLLoader.setPath( 'models/' ); var url = "model.mtl"; MTLLoader.load( url, function( materials ) { materi ...

The error message "POST .../wp-admin/admin-ajax.php net::ERR_CONNECTION_CLOSED" appears when a WordPress AJAX request receives data that exceeds 1MB in size

When I attempt to submit a jquery ajax form from the frontend and upload a blob (a variable of string) as a .txt file to WordPress using wp_handle_upload(), everything works smoothly until the file size reaches around 1mb. At that point, an error is displa ...

Unable to access the computed attribute (array)

My goal is to create a computed property called 'displayImages' that returns an array. The default value of the 'selected' property is set to 0. This property changes based on mouseover and click events. However, when I try to access t ...

Variation in functionality of onclick in javascript

Can you identify the distinction between the two primary lines of JavaScript in this example? HTML: <html> <body> <form> <input type="button" value="one" id="one" /> <input type="button" v ...