The v-data-table fails to refresh with new data

Within my Vuex store, I have an object called portfoliosData which contains a property named metrics.

  state: {
    portfoliosData: {
      performance: [],
      metrics: []
    },

When I trigger an action, I update the property in the store and aim to display these updates in a table.

<div id="amsample">
  <div id="chartdiv"></div>
  <v-tabs-items :touchless="true">
    <v-tabs-content :key="0" id="tab-1">
      <v-card flat>
        <v-card-text>
          Return Performance
          <v-data-table
            :headers="headers"
            :items="metrics"
            :custom-sort="sortPercentage"
            hide-actions
            class="elevation-1"
          >
            <template slot="items" scope="props">
              <td>{{ props.item.name }}</td>
              <td class="text-xs-right">{{ props.item.acRet }}</td>
              <td class="text-xs-right">{{ props.item.anRet }}</td>
              <td class="text-xs-right">{{ props.item.anVol }}</td>
              <td class="text-xs-right">{{ props.item.maxDd }}</td>
              <td class="text-xs-right">{{ props.item.sRatio }}</td>
              <td class="text-xs-right">{{ props.item.inRatio }}</td>
            </template>
          </v-data-table>
        </v-card-text>
      </v-card>
    </v-tabs-content>
  </v-tabs-items>
</div>

The component's table is observing the changes made to the metrics variable.

data() {
  return {
    headers: [
      { text: 'Measure', value: 'name', sortable: false },
      { text: 'Accumulative Return', value: 'acRet' },
      { text: 'Annual Return', value: 'anRet' },
      { text: 'Annual Volatility', value: 'anVol' },
      { text: 'Max Drawdown', value: 'maxDd' },
      { text: 'Sharpe Ratio', value: 'sRatio' },
      { text: 'Information Ratio', value: 'inRatio' },
    ],
    metrics: []
  }
},

After invoking an action in the component, I retrieve the updated metrics from the store.

// Component
calulateMetrics(event) {
  this.$store.dispatch('performeMetricsCalculation', { dataZoomStart: event.startDate, dataZoomEnd: event.endDate }).then(() => {
    this.metrics = this.$store.getters.getMetrics;
    console.log("Calculated metric", this.metrics)
  })
},

// actions
performeMetricsCalculation({ dispatch, commit, getters }, { dataZoomStart, dataZoomEnd }) {
  return new Promise((resolve, reject) => {
    dispatch('performSetRangeTime', { dataZoomStart: dataZoomStart, dataZoomEnd: dataZoomEnd }).then(() => {
      dispatch('performMetrcisUpdating').then(() => {
        commit('resetUpdateStatus')
      })
    })
    resolve()
  })
},

performMetrcisUpdating({ commit }) {
  return new Promise((resolve, reject) => {
    commit('calculateMetrics')
    resolve()
  })
},

While debugging, I noticed that the data in the metrics variable differs from its initial state, yet the table does not reflect these changes.

Within the mutations, I implement the following logic:

calculateMetrics({ portfoliosData, period, status }) {
  let updatedMetrics = []

  for (let s in portfoliosData.performance) {
    if (portfoliosData.performance.hasOwnProperty(s)) {
      let port = { ...portfoliosData.performance[s] }

      updatedMetrics.push({
        name: port.name,
        maxDd: maxDrawdown(port.data, period.startDateIdx, period.endDateIdx),
        acRet: accumulativeReturn(port.data, period.startDateIdx, period.endDateIdx),
        anRet: annualReturn(port.data, period.startDateIdx, period.endDateIdx),
        anVol: annualVolatility(port.data, period.startDateIdx, period.endDateIdx),
        sRatio: sharpeRatio(port.data, period.startDateIdx, period.endDateIdx),
        inRatio: informationRatio(port.data, period.startDateIdx, period.endDateIdx)
      })

      if (!status.isUpdated) {
        portfoliosData.metrics = updatedMetrics
      } else {
        Vue.set(portfoliosData, 'metrics', updatedMetrics)
      }
    }
  }
}

Although there are no problems with updating the table when fetching data without executing an action, the new data does not render when trying to update the table. This discrepancy is peculiar.

This issue is specific to this particular case. Additionally, I attempted to change :items="metrics" to :items=$store.getters.getMetrics but it did not resolve the problem.

Answer №1

Consider updating mutations to:

calculateMetrics(state) {
  let {portfoliosData, period, status} = state // Utilizing ES6 syntax
  let updatedMetrics = []

  for (let s in portfoliosData.performance) {
    if (portfoliosData.performance.hasOwnProperty(s)) {
      let port = {...portfoliosData.performance[s]}

      updatedMetrics.push({
        name: port.name,
        maxDd: maxDrawdown(port.data, period.startDateIdx, period.endDateIdx),
        acRet: accumulativeReturn(port.data, period.startDateIdx, period.endDateIdx),
        anRet: annualReturn(port.data, period.startDateIdx, period.endDateIdx),
        anVol: annualVolatility(port.data, period.startDateIdx, period.endDateIdx),
        sRatio: sharpeRatio(port.data, period.startDateIdx, period.endDateIdx),
        inRatio: informationRatio(port.data, period.startDateIdx, period.endDateIdx)
      })
    }
  }

   portfoliosData.metrics = updatedMetrics
   state.portfoliosData = JSON.parse(JSON.stringify(portfoliosData))
}

To ensure data changes are understood by vuex, creating a new object using the technique of JSON parsing and stringifying is necessary.

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

Get information about mailchimp mailing lists using ajax requests with the iron-ajax element in Polymer

Struggling to access the mailchimp API and display list details? Unsure of how to send authentication credentials to retrieve the information you need? Here are a few attempts that have been made so far: <iron-ajax auto url='https://us3.ap ...

Bringing @angular/code into a directory that is not within an Angular project

Currently, I have an Angular 2 project folder with a separate service folder named "auth.service.ts" located outside of it. Within this service file, I am importing `Injectable` from `@angular/core`. However, due to the service being located outside of t ...

The file input modification event is disregarded if the identical filename is selected for upload

In my Vue.js application, I am utilizing Vuetify's v-file-input component. The file uploaded is connected to formData.file and its validation is controlled by the rules prop. <v-file-input :rules="fileValidationRules" v-model="fo ...

Angular filter is designed to search for elements that contain a specific value, rather than only those that are an exact match

I am currently trying to relate rules to fields using the 'filter' filter in Angular. You can see an example of this implementation here: http://plnkr.co/edit/dQiv5lRzhQNjXZ6pVdWO?p=preview The code I am using for this purpose is as follows: &l ...

Parsing values from deeply nested objects and arrays

I've come across this issue before, but I'm having difficulty navigating through a nested structure. I can't seem to find any guidance in the right direction. Here is the object I'm attempting to parse: const nestedArray = { id ...

The Functionality of Accordions

I have created a responsive accordion script that functions smoothly and allows for easy access to content within each drawer. Unlike many accordions, this one does not cause issues with positioning after opening. The code I am using includes a toggle acti ...

How to use jQuery to select nested elements in ASP.NET?

I'm struggling to understand why this selector is correctly targeting the txtUsername element: aspx: <asp:Content ID="Content1" ContentPlaceHolderID="body" runat="Server"> ... <div class="copy" style="float: left; width: 210px"> ...

Checkbox no longer has an underline when it is checked

My goal is to develop a Todolist app using express.js and node.js. The idea is that when a user checks a checkbox for a task, that specific data in the array should be underlined. However, this feature is not working when I try to implement it via HTTP pos ...

What is the method for accessing the locale and messages of the IntlProvider within a component?

My index.js file includes the following code: import trFi from './translations/fi_FI.json'; import trSv from './translations/sv_SE.json'; ReactDOM.render( <IntlProvider locale={my_locale} messages={{ fi: trFi, sv: trSv } ...

Guide to displaying a particular item in Vue 3

Currently, I am embarking on a project that requires the functionality to print a specific element of my webpage. After some research, I came across a mixin/plugin known as VueHtmlToPaper which seems to be the perfect solution for what I need. However, I a ...

Find the highest value in a MySQL column

Currently, I am working with a mysql table in NodeJs where there is a column called packageId. My goal is to fetch the highest value from that particular column. For instance, if the values in the column are 2,3,4,5, I only want to retrieve 5. I attempted ...

Tips for displaying an input element across multiple cells in ObservableHQ

Imagine you have the code snippet below representing a checkbox element in Observablehq: viewof myFilter = checkbox({ title: "Foo", description: "bar", options: myOptions, }) How can I display this element multiple times in different cells through ...

The function 'send' cannot be called as it is undefined (response is undefined) within Express.js

I have encountered a challenge while trying to pass a variable from my index.html to the database (maildata.js) through app.js (server) and retrieve the corresponding data. I have successfully retrieved the data from the database, but I am facing difficult ...

Adding JSON information to various elements

I'm looking for a more efficient way to use a switch statement in order to create markups based on the retrieved feed. Although I am currently able to successfully retrieve the data, I'm not sure if it's the best approach to use two $(data.v ...

The jQuery modal window is not appearing when trying to fade in

I want to set up a feedback form where all fields are filled out and the user has clicked the checkbox confirming they are not a robot. Once this is done, the Send button becomes active and a popup window will appear with a message saying "Thank you, we wi ...

Problem with loading messages in VueI18n locale

Utilizing the vueI18n package for language localization in our application, we fetch the locale messages object via an api call. Within our config file, we have specified the default language which is used to load the locale before the creation of app.vue. ...

Prevent inheriting styles with jQuery Else / If conditions

I'm seeking advice on how to prevent elements from retaining the same inline styles in different breakpoints. My goal is to adjust styling based on window width, similar to CSS media queries, but with the additional need to increment a numeric value ...

Changing the designated materialUI class

Within the project, I am utilizing this theme: export const theme = createMuiTheme({ ...defaultThemeConfig, overrides: { ...defaultThemeConfig.overrides, MuiListItem: { root: { '&:nth-child(odd)': { backgro ...

Oops! Looks like there was a mistake. The parameter `uri` in the function `openUri()` needs to be a string, but it seems to

While working on my seeder file to populate data into the MongoDB database, I encountered an error message that reads: Error : The `uri` parameter to `openUri()` must be a string, got "undefined". Make sure the first parameter to `mongoose.connect()` or `m ...

What are the steps to retrieve historical stock data for over one year using Yahoo Finance YQL query?

I am currently using a Tableau web connector to retrieve stock price data. Here is the source code: <html> <meta http-equiv="Cache-Control" content="no-store" /> <head> <title>Stock Quote Connector-Tutorial</title> <sc ...