I am encountering a problem with my Vuex getter where it is sending an Array with a length of 0, but when expanded in the console,

Currently, I'm utilizing Vuex to interact with a Django API in order to fetch count data.

state: {
    DailyCycleDate: []
},

getters: {

  DailyCycleDate : state => {
    console.log('Getter')
    console.log('Length of Array: '+state.DailyCycleDate.length)
    console.log(state.DailyCycleDate)
    return state.DailyCycleDate
  }
},

mutations: {

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

      let NewList = []

      NewPatientMap.forEach((value, key) => {
        var NewPatientCycle = value['Current_Cycle_Date']
        console.log('inside mutation')
        state.DailyCycleDate.push(NewPatientCycle)
      });

    }
 },

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

Strange enough, when I check the console log, it shows an empty array:

https://i.sstatic.net/HdxhR.png

I'm curious as to why this array has turned empty. Is there some synchronization issue occurring? Despite trying promises and Timeout methods, the array remains at 0. How can I view the essential data while the array stays empty?

Could there be an object embedded in the array causing this? I attempted transforming it into an object and mapping it as well. Any suggestions or advice would be highly valued!

Thank you,

It's also important to mention that I require this data to populate the label field of a ChartJS barchart

export default {
  extends: HorizontalBar,
  data() {
    return{
    }
  },
  mounted () {
    /* Need to write the API call for chart data here. */
    this.$store.dispatch('DailyCountAction')

    this.renderChart({
    labels: [this.$store.getters.DailyCycleDate],
    datasets: [...]

Answer №1

state.DailyCycleDate's .push() method doesn't update the reference of state.DailyCycleDate.

To recalculate getters, you must update the reference of state.DailyCycleDate.

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

    let NewList = []

    NewPatientMap.forEach((value, key) => {
      var NewPatientCycle = value['Current_Cycle_Date']
      console.log('inside mutation')
      NewList.push(NewPatientCycle)
    });
    state.DailyCycleDate = state.DailyCycleDate.concat(NewList)
  }
}

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 best way to avoid routing before certain async data in the Vuex store has finished loading

I am facing a challenge in my application where I require certain data to be loaded into the VueX store before routing can commence, such as user sessions. An example scenario that showcases a race condition is as follows: // Defined routes { name: &ap ...

Experiencing the "Module not found" issue while incorporating SCSS into React applications

I attempted to apply a SCSS style to my "Logo.js" component, but I am still unable to resolve the error that keeps popping up: ERROR in ./src/components/Logo/Logo.js 5:0-19 Module not found: Error: Can't locate 'logo.scss' in '/Users/a ...

Adhering button for sliding side panel

Check out my JSFiddle HERE to see what I have done. I would really appreciate it if someone could help me figure out how to make the show button float with the sidr panel :) <style type="text/css"> #panel { position: fixed; top: 50%; r ...

Separate a string using commas but disregard any commas inside quotation marks

Similar Question: JavaScript code for parsing CSV data There is a string that looks like this: "display, Name" <<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="3d49584e497d49584e49135e5250">[email protected]</a> ...

Does Koa.js have a nested router similar to Express?

Are there any libraries available that offer Express-style nested routers? For example: var koa = require('koa'); var app = koa(); var Router = require('???'); var restApiRouter = Router(); restApiRouter.get('/', function*() ...

Preventing Content Jumping When Concealing Elements: Tips and Tricks

I've been working on a project at , where you can click on a small map to expand a larger map below it. However, I noticed that when you scroll down to the large map and then try to close it using the button at the bottom, the content on the page jum ...

How can I organize the selected options from a select2 form element using a basic sorting method?

I am utilizing select2 by ivaynberg and encountering an issue with the data arrangement upon submission. Is there a method to have the results in the form submit data reflect the order in which they were selected in the select2 element, without relying on ...

Encountering a segmentation fault error, yet at a loss for how to resolve it

I am struggling with a code that is causing a segmentation fault, and debugging it has been challenging for me. It seems like my lack of knowledge in C syntax might be the reason behind this issue, even though I have already gone through TCPL. #include ...

Ways to restrict the maximum length in Draft.js

Is there a way to control the maximum number of characters in draft js? I know how to get the length of the state, but is there a method to prevent the component from being updated past a certain point? var length = editorState.getCurrentContent().getPla ...

What precautions should I take when setting up my login routes to ensure security?

I am working on developing a login and registration system for a website project, but I'm unsure about the best way to safely implement the routes/logic for it. Currently, in my client-side code, I make fetch requests to either the login or register r ...

Using jQuery to dynamically insert variables into CSS styles

I am attempting to use jQuery 3 to modify the CSS of a class and change the background color. My first step is converting an rgba color code (properties.color) to a hexadecimal code, which is functioning correctly. Next, I try to change the background co ...

Generate unique identifiers in HTML

Below is my HTML and JavaScript code: <!DOCTYPE html> <html> <head> <style> .custom-div { border: 1px solid green; padding: 10px; margin: 20px; } </style> <script> ...

The resolve in Angular UI-Router is not being properly injected into the controller

As a Java developer venturing into the world of Angular and Express, I am encountering challenges along the way. To gain hands-on experience, I am attempting to create a small application using these technologies. The Goal: I have provided a password rese ...

Issues with Initializing Byte Arrays in C++ - Where Are We Going Wrong?

I'm currently facing an issue with a byte array in a C++ project for Arduino. The bytes are #defined in a different file that is generated elsewhere and then imported into my project. However, I'm noticing that the first two bytes in the array ke ...

Guide on serving Vue's static dist folder using express with app.use('someRoute')

I have encountered an issue while serving a dist folder from a vue app (created with create-vue-app). Everything works fine when I use the root route without specifying any sub-routes. However, when I point to a specific sub-route like '/static', ...

Error encountered: The token transfer cannot be completed due to an invalid address

Whenever I attempt to send a token from one address to another, I keep encountering the error mentioned in the title. Below is the relevant snippet of my JavaScript code: tokenContract.transfer($("#targetAddr").val().toString(), $("#amt" ...

Leveraging react router within next.js

I am currently delving into the realm of Next.js/React for my project and seeking to understand the intricacies of routing. One question that has cropped up during my research is whether I need to incorporate react-router with Next.js, given my previous ex ...

The Ajax call is failing to trigger the success function

Can anyone assist me? My success function isn't working properly. The beforesend is functioning correctly and I've verified the variable s. It has a true value before the ajax call, so all validations are correct. Please take a look... function ...

The Meteor update is unsuccessful on the Mongo Sub Collection and will not continue

I am currently facing an issue with updating a specific object within an array in my object based on a value. Whenever I try to add the update code, the function gets stuck at that point without proceeding further. None of the console.log calls after the u ...

Effective methods for eliminating timezone in JavaScript

I need to display the time and format {{transaction.submitTime | date:'yyyy-MM-dd HH:mm:ss Z'}} Currently, it displays 2015-04-23 02:18:43 +0700 However, I would like to show the time without +0700, where the hour will be incremented by 7. Is ...