My Vuex component is not updating when the state changes

My component is not reacting to Vuex store changes when I edit an existing element, even though it works fine when adding a new element. After hours of debugging and trying everything, I've realized that it might have something to do with deep watching the store changes.

For example, when I add an element to currentVisit.pathologies like {id:1,title:"Something"}, it works fine. But when I try to edit an element, my component does not react to the store update.


UPDATED 

addPathology: (state, payload) => {
      state.currentVisit.pathologies.push(payload);
    },
    updatePathology: (state, payload) => {
//This condensed code snippet highlights the issue with my component not reacting.
      state.currentVisit.pathologies[0] = payload;
    }
state{
currentVisit: {
      id: "5",
      tumors: null,
      pathologies: [],
      examinations: null,
      allergies: null,
      diagnoses: null,
      comorbidities: null,
      chemotherapies: null,
      radiations: null,
      immunotherapies: null,
      operations: null
    }
}

createPathology: ({ commit, getters }, payload) => {


      return new Promise((resolve, reject) => {
        //do axios
        //then commit updatePathologies
        //then return promise response
        baseAxios
          .post("visits/" + getters.visitId + "/pathologies", payload)
          .then(res => {
            commit("addPathology", res.data.data);
            resolve(res);
          })
          .catch(e => {
            reject(e);
          });
      });
    }

editPathology: ({ commit, getters }, payload) => {

      return new Promise((resolve, reject) => {
        baseAxios
          .patch(
            "visits/" + getters.visitId + "/pathologies/" + payload.id,
            payload
          )
          .then(res => {
            //commit("updatePathology", res.data.data);
            resolve(res);
          })
          .catch(e => {
            reject(e);
          });
      });
    }

Answer №1

Revamp the updatePathology mutation to enhance reactivity:

updatePathology: (state, payload) => {
  const pathologies = state.currentVisit.pathologies;
  pathologies[0] = payload;
  // create a new array reference for better reactivity
  state.currentVisit.pathologies = [...pathologies];
}

Vue Documentation

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

Why isn't changing the property of a Sequelize instance having any effect?

While I've successfully used the standard instance syntax in the past, I'm facing a challenge with updating an instance retrieved from the database in this specific section of my code. ... const userInstance = await db.models.Users.findOne({wher ...

Is the for loop programmed to stop at the first match?

I've been working on filtering a txt file using nodejs. Here's my code snippet: const fs = require('fs') let list = fs.readFileSync('./newmR.txt', 'utf-8').split('\r\n') console.log(list.length) ...

Why is the background image not loading properly on first hover with CSS?

Whenever we load a page with a large image set as the background for a div, there seems to be a delay in displaying the image when we hover over the div. Is there a solution to this issue? I would prefer not to use a sprite image because I need to make alt ...

Guide to changing text value for translation with api

I'm interested in creating an application that can translate English text into Yodish, but I'm struggling with indicating the value of my text box. Currently, I'm attempting to access the data text properties. While I've been able to r ...

Unraveling JSON data within an AngularJS controller

I'm facing an issue with exposing a field in my AngularJS controller. The problem arises when a JSON 'owner' object is returned by a webservice, containing a field named 'Cave'. If this 'Cave' field has a null, empty, or ...

Experiencing difficulty with loading elements into their respective containers

My goal is to limit the number of alert elements loaded in each .content container to a maximum of 9, but currently I am grouping every 10 items together and discarding any remaining items! For instance, if a random value is 8, then no content will be dis ...

Unable to detect errors using React/Redux

I encountered a login error handling issue with redux that is structured like this: export const login = (params: any) => async (dispatch: Dispatch) => { try { const authData = await API.post("login", params); sessionStorage.setIt ...

What is the proper way to type a collection and put it into action?

I am looking for a way to create an object that mimics a set. Specifically, I want the transaction id to act as a key and the transaction details as the value. To achieve this, I created the following: type TransactionDetail = { [key: TransactionId]: Tra ...

Ajax request results in a 400 error code

Here is the structure of my Ajax call: function Submit() { var objectData = { email: $("#email").val(), firstName: $("#firstName").val(), lastName: $("#lastName").val(), loginMode: $("#login ...

What is the best way to inform the DOM about newly generated elements dynamically?

When making an AJAX call and generating HTML on the backend side, the result may not display with the desired properties such as cursor styling. For example, using jQuery to render JSON data: $(data.message).each(function (index, value) { $('#sta ...

Value of type 'string' cannot be assigned to type '{ model: { nodes: []; links: []; }; }'

I am a beginner in TypeScript and I have added types to my project. However, I am encountering an error with one of the types related to the graph: Type 'string' is not assignable to type '{ model: { nodes: []; links: []; }; }'.ts(2322) ...

Difficulty managing Browser Cookies within vue.js

Having an issue with a plugin handling browser cookies in vue.js The plugin was installed, imported in main.js, and configured as shown below: import { createApp } from "vue"; import { createPinia } from "pinia"; import { globalCookies ...

Button within the Magnific Popup (do not use to close)

I am currently developing a website with a gallery page that utilizes the Magnific Popup plugin. My client has provided lengthy 'captions' for each image, almost like short stories. To display these captions effectively, I have utilized the titl ...

Troubleshooting a Multi-dimensional Array Reference Issue

Currently, I am working with an Array and need to modify the last item by pushing it back. Below is a simplified version of the code: var array = [ [ [0,1,2], [3,4,5] ] ]; //other stuff... var add = array[0].slice(); //creat ...

Discovering the window scroll unit when clicking, as a page smoothly transitions to the top for a specified target position

Is there a way to achieve parallax scrolling on window scroll and navigation click simultaneously? When navigating and animating the page to the top to show the target, I also want to get the window scroll unit. How can I obtain the window scroll unit on ...

the order of initialization in angularjs directives with templateUrl

In my current scenario, I am faced with a situation where I need to broadcast an event from one controller and have another directive's controller receive the message. The problem arises because the event is sent immediately upon startup of the contro ...

transforming a text input into unadorned plain text

Currently, I am in the process of creating a small HTML form that consists of a single textbox input. Once the user enters text into this textbox and clicks on a button located at the end of the page, I would like the textbox to transform into normal plain ...

Discover how to fetch data within Vue component using data access object in Vue 3

I am in the process of utilizing a data access object (dao) named Todos.js to fetch necessary data for a Vue3 component called List.vue. Below, you will find snippets from my code as an example. Upon initializing the application, the data is successfully ...

Triggering jQuery Submit Form when Form is Modified

I need help with automatically submitting a form using jQuery when an input changes. The specific input I am working with is a date picker, and I want the form to be submitted as soon as a user makes a selection. <form id="select_date" name="select_da ...

Switch Background Image - The image failed to display

Here is the code snippet I am currently working with. It involves displaying a background-image when clicking on a link with the class 'home-link', and not showing an image if the link does not have this class. The issue at hand: The problem ari ...