Vue is failing to detect changes in the object retrieved from Vuex

I am facing an issue where Vue only sees the first update of an object stored in Vuex. The object is collected step by step, starting empty and then being updated through commits to the Vuex state like setUser. While I can see the new information reflected in Vue DevTools after using addInfo commit, it doesn't display on the page and remains stuck at the second state.

async fetchUser({ commit, state }) {
  return new Promise(() => {
    axiosInstance
      .get(User(), {
        headers: {
          Authorization: 'Token ' + localStorage.getItem('token'),
        },
      })
      .then((res) => {
        commit('setUser', res.data);
      })
      .then(() => {
        axiosInstance.get(UserID(state.userInfo.pk)).then((res) => {
          axiosInstance.get(res.data.profile).then((res) => {
            commit('addInfo', res.data);
            console.log(state.userInfo);
          });
        });
      })
      .catch((err) => {
        console.log(err);
      });
  });
}

The userInfo object is fetched and displayed on the page using:

computed: {
    ...mapGetters(['userInfo']),
},
created() {
    this.$store.dispatch('fetchUser');
}

This is the current content displayed on the page

This is how the object actually looks like

Answer №1

If you're experiencing a common reactivity issue, there are various solutions that you can explore:

Within Vue, there is a limitation in detecting property additions on objects due to JavaScript constraints. To address this, ensure that your initial state.userInfo contains all the keys you anticipate needing for reactivity. You can simply set these keys to null, '', or 0 based on their data type.

userInfo: {
//all my userInfo reactive keys
 1stkey: '',
 2ndkey: null,
 3rdkey: 0,
 ...
 100thkey: '',
}

Additionally, consider setting state.userInfo = null initially so you can monitor when it becomes populated.

To delve deeper into Vue reactivity, refer to Vue Reactivity within the 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

Error Occurs When Trying to Utilize Imported React Selector in React Actions Script

Desired Action: I am looking to utilize a state value within one of my action methods. Preferred Approach: Instead of directly referencing state.sale.oliver.data, I aim to abstract it by invoking my selector function, showingTest(state). Issue Encountere ...

Encountering difficulty in adding content to a table using JavaScript. An error message appears stating that assignment to a function

I am utilizing ajax to retrieve an item from a web API, and then attempting to allocate attributes of that item to a table: function find() { var id = $('#contentID').val(); $.getJSON(uri + '/' + id) .done( ...

Tips for fixing CORS error when working with the fetch API

I'm having trouble retrieving data from the metaweather.com API using JavaScript's fetch function. I attempted to include before the API URL, but it has not resolved the issue. I followed a video tutorial on how to fetch data, but I'm stil ...

React Weather App experiencing issues with prop communication and updating variables

My innovative weather app allows users to input custom longitude and latitude coordinates. Once the coordinates are received, they are passed as props to a child component where they are used in an API call to fetch data for that specific area. While ever ...

Conceal a button using an AJAX POST request

I'm encountering an issue with my Ajax post where I am trying to disable the button used to submit data. I've reviewed my code and it seems accurate, but the button is not getting disabled. I attempted using $("#refreshButton").attr("disabled", t ...

Converting an HTTP request and incorporating a success function in Typescript and Angular2

I am working on a http request: private getValues() { this._watchlistElements.map(v => this.http.get('http://localhost/getValue/' + v.xid) .subscribe(res => { this._values.push(res.json()); })); }; When the request ...

How can the ordering of dynamically generated components be synchronized with the order of other components?

Currently, I'm delving into Vue 3 and encountering a specific issue. The tabs library I'm using only provides tab headers without content panels. To work around this limitation, I've come up with the following solution: <myTabs/><!- ...

How can you retrieve an array of multiple property values from a collection of dynamic objects?

I am currently working with a dynamic JavaScript object array that has varying structures. For example: var someJsonArray = [ {point: 100, level: 3}, {point: 100, level: 3}, {point: 300, level: 6} ]; At times, it may have a different combination lik ...

Invoking a method within the same class in Typescript can be achieved by calling one method from another

I've recently delved into Typescript and I'm facing an issue when trying to call one method from another method within the same class. After researching this problem, some individuals suggested using "this" before the method name. However, in my ...

Implementing auto-complete functionality using two keys in Material UI and React

My goal is to enable autocomplete for input when searching with values like title and year. Strangely, the autocomplete feature only works when I search with title. Searching with year does not yield any options. Sample code export default function ComboB ...

Eliminate inner margin from the canvas of a bar chart created with ChartJS

I am looking to use Chart.js to create a single stacked bar chart that visualizes progress towards a specific financial goal. I have added a dotted line on top of the chart to represent this goal amount. The issue I am facing is that there is unwanted pad ...

The output from the console displays a variety of numbers (11321144241322243122)

Every time I attempt to log the number 11321144241322243122 into the console, it consistently converts to a different number 11321144241322244000. This issue persists both in node.js and the browser console. ...

"Trouble with Angular's http.get method failing to retrieve data from MySQL through Node

I am struggling to retrieve data from MySQL using Angular and Node.js. Despite trying, I am unable to make it work. When I check Postman using the link http://localhost:8080/locations, I can see the data. { "status": "200", "items": [ { "cit ...

Google Chrome is unable to process Jquery JSON .each() function

My website has a simple chat application that is functioning well. It uses ajax to request data in this manner: $.ajax({ url: "fetch/"+CHAT_SESSION_ID+"/"+LAST_MESSAGE_ID, dataType: "json", cache: false, success: function(data) { if (data.session_ac ...

How come my image is not appearing on Vue.js when fetched from the API?

While working on my laravel vue project, I encountered an issue where the image is not being fetched from the backend API. All other data is being displayed correctly except for the image. JSON: [ { "id": 1, "name": ...

Encountering issue - SCRIPT5022: Error parsing message from server in Sys.WebForms.PageRequestManagerParserErrorException

I'm in need of assistance. I've developed a web application in .Net 3.5 that utilizes asp.net Master page, update panel, and server controls. The asp.net page created with the Master page includes an update panel that contains other server contro ...

Styling for inactive buttons not being implemented

I'm having trouble applying disabled styling to a button component using SCSS. The button has multiple classes: <button className="button button--size-short-wide button--secondary" data-cy="letters-compose-message-content-add-ph ...

"Utilizing the 'await' keyword within a JavaScript 'for of'

Could there be an issue with my code? I am utilizing express and mongoose router.get('/c/:hashtoken', validateEmailToken, catchAsync(async(req,res)=>{ const hashtoken = req.params.hashtoken const hashtoken2 = createHash('sha256&ap ...

The function .css() in jQuery is malfunctioning

This task should be a piece of cake... All I want is to hide the buttons when a user is logged in and display the log out button instead. jQuery().ready(function($) { if ($("body").hasClass("logged-in")) { $(".logged-out-button").css("display", " ...

Troubleshooting Guide: Resolving npm Error Code EINVALIDTAGNAME During Package Publishing

node -v 20.18.0 npm -v 10.9.0 Hey there! I've encountered an issue - whenever I attempt to use any npx init command, I encounter an error. For instance, npx init prisma The same error occurs when I try to initialize husky. PS C:\Users\User ...