Problems with Vuex getter reactivity when used in conjunction with Vue router

I've encountered an issue with my Vuex getter that fetches data for the current route and displays it in a Vuetify v-data-table. Everything works perfectly fine when the component is initially created. However, when I add a new entry to the data array in the state that the getter interacts with, the new entry is only displayed after navigating away from the current route. I'm using the current route as a key to differentiate between entries in the state so that I can show different information based on the current route, utilizing Vue router. If my explanation is unclear (English is not my first language), here's some relevant code: The getter in question:

  computed: {
    ...mapGetters({
      geData: "geData"
    }),
    getAllData() {
      return this.geData[this.$route.path];
    }
  }

The data table:

<v-data-table :headers="headers" :items="getAllData" hide-actions>
  <template v-slot:items="props">
        <td class="text-xs-left">{{ props.item.name }}</td>
        <td class="text-xs-left">{{ props.item.state}}</td>
        <td class="text-xs-left">{{ props.item.created_at }}</td>
        <td class="text-xs-left">{{ }}</td>
      </template>
</v-data-table>

This is how I update the array in the store mutation:

  setNewData: (state, Data) => {
    state.Data[Data[0]] = Data[1];
  }

The first Data[0] represents the route used as a key, while the second Data[1] contains the new data. I suspect that the getter only updates when navigating away from the current route because of the usage of the route as a key. However, I'm unsure and do not know how to address this issue. Any ideas or suggestions would be greatly appreciated. Thank you in advance!

Answer №1

If you want your object keys to be reactive, remember to use Vue.set as they must be declared first:

Vue.set(state.Data, Data[0], Data[1])

This will ensure the reactivity you need in your code.

Quick tip:

Always initialize state.Data as an object to guarantee its reactivity from the start.

Answer №2

Give this a try:

updateData: (state, newData) => {
  Vue.set(state.data, newData[0], newData[1])
}

Make sure to import Vue if it's not already included in your file.

For more details, check out https://v2.vuejs.org/v2/guide/reactivity.html#Change-Detection-Caveats.

This solution assumes you are adding a new property to the object. If the property already exists, there is no need for Vue.set.

Another approach could be to create a copy of the object and add the new property before making it reactive:

updateData: (state, newData) => {
  state.data = {
    ...state.data,
    [newData[0]]: newData[1]
  }
}

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

Vue-Resource fails to set Authorization header

Having trouble setting the authorization header to "Bearer (token)" in the main.js file after signing in. It shows a 401 unauthorized error, but the headers are set correctly after refreshing when accessing the files list from the server. More Details: S ...

Acquiring images from an external source and storing them in either the $lib directory or the static folder during the

Currently, I have a Sveltekit project set up with adapter-static. The content for my pages is being pulled from Directus, and my images are hosted in S3, connected to Directus for easy access. I am also managing audio samples in a similar manner. During b ...

Is it possible to pass a JavaScript array to a local variable by reference?

Within my namespace, I have an array defined in JavaScript like this: app.collection.box = []; Additionally, there is a function within the same namespace structured as follows: app.init = function () { var box = this.collection.box; // ... code ...

Even though the Spotify API JSON response may be undefined, I am still able to log it using console.log()

Trying to utilize Spotify's Web Player API in order to retrieve the 'device_id' value has been a challenge. The documentation states that the server-side API call I am supposed to make should result in a 'json payload containing device ...

Guide to setting up a datePicker in a cellEditorSelector

In my grid, I want to have different editors for different rows within the same column. The ag-Grid documentation provides information on how to achieve this using colDef.cellEditorSelector as a function: link I have successfully created unique editors fo ...

Export data from Angular Material data table to Excel format

I'm currently utilizing the angular material data table to showcase data in a tabular layout. I have a requirement to add a feature that enables the export of tabular data to an Excel sheet. Unfortunately, I haven't been able to locate any resour ...

Mongoose/JS - Bypassing all then blocks and breaking out of the code

If I need to check if a certain ID exists and exit the process if an error is encountered right from the beginning, is there a more concise way to do it rather than using an if-else block? For example: Question.find({_id: req.headers['questionid&ap ...

"Adding properties to objects in a map: a step-by-step guide

During my attempt to add a property within a map loop, I noticed that the update appeared to occur on a duplicate rather than the original object. MY_ARRAY.map(function(d){ d.size = DO_SOMETHING }); ...

Tips for enabling/disabling a Chrome extension through the utilization of local storage in the background page

Even after reading numerous answers on similar questions, I am still facing some difficulties. My goal is to allow the user to disable my chrome extension by simply clicking on the icon at any time. The extension is designed to run once on every page load, ...

Increase the totalAmount by adding the product each time

Can someone help me understand why the totalAmount shows as 20 when I add a product? Also, why doesn't it increase when I try to increment it? Any insights would be appreciated. Thank you. ts.file productList = [ { id: 1, name: 'Louis ...

Switch Button Hyperlink in HTML/CSS

I have the following code: document.addEventListener("DOMContentLoaded", function(event) { (function() { requestAnimationFrame(function() { var banner; banner = document.querySelector('.exponea-banner3'); banner.classList ...

The request.body in Express.js is currently undefined

const express = require('express'); const cors = require('cors'); const app = express(); app.use(express.json()) app.use(cors()); app.post('/', (req,res) => { console.log(req.body); res.send('received') ...

Concealing Navigation Links in VueJs Upon Being Clicked

I've been trying everything to get the navigation links to hide when I click on them, but so far nothing has worked. Here's a snippet from my Header.vue file: <template> <nav class="navbar is-dark is-fixed-top"> <div class="co ...

Semantic-release failing to generate a new version update for package

I'm in the process of setting up semantic release for my NPM package to automate deployment with version updates. However, after migrating from an old repo/npm package to a new one, I'm facing issues with semantic versioning not creating a new re ...

Exploring Ancestors with Jquery to Find Input Fields

In my current project, I am working on a function that needs to extract the values from two input fields within a specific div element. These values will then be added to an array and posted as JSON data. However, I am facing difficulties in navigating thr ...

Using jqGrid to load additional JSON data after the initial local data has already been populated in the

I encountered a specific issue: I have a compact form with four choices. Users can choose to fill them out or not, and upon clicking 'Ok', a jqGrid is loaded with data based on those selections. To accommodate dynamic column formatting, my servle ...

I am struggling to extract data from the spawned Node.js child process. What am I overlooking?

Trying to utilize a spawned command-line process for lzip in order to expand an lzipped data stream due to the lack of suitable native JavaScript tools. Succeeded in achieving this by working with files and file descriptors, although cumbersome to handle ...

The process of displaying only the month name as the title in Full Calendar

Is there a way to display the Full Calendar title with only the month name instead of "month name year name"? Here is my code attempt: $('#calendar').fullCalendar({ header: { left: 'prev', center: 'title' ...

Encountering an error when attempting to parse a JSON Object in Java from an AJAX call

** Latest Code Update ** My JavaScript and Ajax Implementation: $(function() { $("#create_obd").bind("click", function(event) { var soNumber = []; $('#sales_order_lineItems input[type=checkbox]:checked').eac ...

Nginx Reverse-Proxy Configuration Problem: Dealing with Rewrite or Internal Redirection Loop involving VueJS SPA and GraphQL Backend

I've developed an application that combines the backend (GraphQL API) and frontend (VueJS SPA) on a single endpoint: /graphql => Backend endpoint (no additional routes needed here) / => SPA (index.html, History-Routing) The SPA utilizes Histor ...