Issue with Vue reactivity in updating global state

Having some difficulties with updating the global state. I've been attempting to update the state by listening to WebSocket, but it's not updating as expected. Here is how I have defined the global state:

state: {
        userData: null
},
getters: {
  userData: state => {
        return state.userData
},
mutations: {
   GET_USER({payload}) {
  commit('GET_USER', payload)
},

I am making updates in App.vue like this:

mounted() {
        window.Echo.channel("user." + this.userData.id).listen(".user-updated", (user) => {
              this.$store.commit('GET_USER', JSON.stringify(user.user))
        });

I also tried using localStorage, which seems like a valid alternative, but I prefer using the global state. If I were to use localstorage, it would look like this:

      localStorage.setItem('userData', JSON.stringify(user.user))

When I want to display that data in a component, such as Home.vue, the only way I can see what is happening is by including

{{ this.$store.getters.userData }}
in the template of that file. However, if I try to define it in the script data section, like so:

     data() {
             return {
                 data: this.$store.getters.userData,
             }
        },

It does not update in real time, only when I navigate to another page and return here or manually update the component. Any ideas on how to resolve this?

Answer №1

My approach to achieving success was through accessing the state. It is my understanding that this should be reactive using this.$store.state.userData to reflect the current state of the store effectively.

It's important to note that accessing object properties may not be as reactive as you expect: https://v2.vuejs.org/v2/guide/reactivity.html#For-Objects
Therefore, it is advisable to define a getter for accessing the user's name, credentials, or any other information stored in userData.

A more explicit approach would entail defining every property of the userData object in the store and creating a mutation for each property individually (although loops can be used for efficiency, mutators still need to be created).

{
  state: {
    userData: {
      id: null,
      name: '',
      email: '',
      // etc.
    }
  },
  // ...
}

This method can also work effectively alongside the getter that you have defined.

In my experience, I prefer not to rely on handling entire objects at once. While it may require additional code to write, explicitly defining the expected properties of the object brings value to both yourself and others.

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

Stopping a NodeJS script execution: Tips and Tricks

While working on my NodeJS application, I've noticed that occasionally my CPU usage spikes to 100%, but there is no memory variation. This causes my Event Loop to become blocked by the operation. I recalled how browsers handle problematic scripts by ...

Implement the useEffect() function to handle the loading of external JavaScript on the client-side, replicating the

I have encountered a challenge while trying to integrate a rich text editor into my NextJS project. Since there are no available React components for this specific editor and it operates solely on the client side, I am required to load the necessary JavaSc ...

Limiting access to multiple Node.js applications on a machine with multiple IPv4 addresses

Setting up a Ubuntu 19.10 machine with one to two wired network interfaces and multiple IP addresses assigned to each interface, for example, 10.0.0.1 and 10.0.0.2. Is there a way to run two identical Node.js applications where the first one uses the IP a ...

What is the best way to focus on a specific section of a CSS class name?

Successfully Working Example: HTML: <div class="items"> <div class="item">item 1</div> <div class="prefix-item-suffix">item 2</div> <div class="item">item 3</div> < ...

Exploring Vue 3.3: Understanding Generics and Dynamic Properties

I'm currently diving into the generics feature in vue 3.3 and I've been pondering about defining the type of an incoming prop based on another prop value. This is my current component structure: export interface OptionProps { id: string | numb ...

NextJs not processing Bootstrap form submissions

I’m struggling to figure out why my form isn’t submitting when I click the submit button. The backend seems fine because Postman successfully sends the information to the database. However, nothing happens when I try to submit the form. My tech stack ...

Ways to include multiple pieces of data in a JQuery Mobile List view

Obtaining JSON data (list of available Hotels within a certain distance) and extracting the following information in JSON format: Name of Hotels, Distance of Hotel from our current location, number of rooms. There might be multiple Hotels within the specif ...

Conceal certain components when a user is authenticated

Below is the content of my app.component.html: <nav class="navbar navbar-expand-lg navbar-light bg-light"> <div class='container'> <ul class="nav navbar-nav"> <li class='nav-item'> <a clas ...

Employ the faker.js library to automatically create a form within casperjs environment

When using Casperjs to fill and submit forms, it is necessary to manually input the data each time. On the other hand, Faker.js can generate fake data that can be used in forms. The question then arises - how can these two be combined effectively? Consider ...

"Can you provide instructions on how to set the background to the selected button

How can I change the background color of a selected button in this menu? Here is the code for the menu: <ul id="menu"> <li class="current_page_item"><a class="button" id="showdiv1"><span>Homepage</span></a></ ...

establish the data type for the key values when using Object.entries in TypeScript

Task Description: I have a set of different areas that need to undergo processing based on their type using the function areaProcessor. Specifically, only areas classified as 'toCreate' or 'toRemove' should be processed. type AreaType ...

Toggling the visibility of a div using JavaScript

When I click the button, I want to show and then hide a div. However, it doesn't work on the first click - only on the second click. How can I make it work on the first click? HTML <p>Click the button</p> <button onclick="myFu ...

Array Filtering Results in an Empty Array of Objects

I'm currently attempting to filter out all objects from the projects array that do not appear in the savedProjects array, but I'm ending up with an empty result. Could it be that I am approaching the filtering process incorrectly? Here's my ...

Processing of hierarchical JSON structure

I have a JSON array that I am trying to duplicate only once while keeping it unique. Here is the code I have attempted: return_data = {}; return_data.planner = [{ "date": "2019-08-30T12:10:08.000Z", "event": [{ "name": "Event 1", "col ...

Transferring dynamic parameters from a hook to setInterval()

I have a hook that tracks a slider. When the user clicks a button, the initial slider value is passed to my setInterval function to execute start() every second. I want the updated sliderValue to be passed as a parameter to update while setInterval() is r ...

Include criteria in my ajax call (conditional statements)

Is there a way to add conditions to my ajax request? Whenever I include the code below, it only seems to work for one item at a time. $.ajax({ type: 'GET', url: urlPost, success: function (data) { $.each(data, function (key, value) { ...

Can we create dynamic v-for variables in Vue.js?

<div class="col-3" v-for="n in 5" :key="n"> <h3>Table {{n}}</h3> <draggable class="list-group" :list="`list${n}`" group="people" @change="log"> ...

Organizing dates with Javascript

Is there a way to convert a string from this format : 2014-06-12T23:00:00 To another format using JavaScript, like so : 12/06/2014 23:00 ...

A guide to determining the length of an object in Vue.js

Looking to implement form validation functionality with VueJS. Encountering an issue while checking the length of the error object. In the console, it returns undefined when using this.errors.length. It seems to interpret .length as a key within errors. ...

What is the best way to refresh jCarousel following the loading of AJAX content?

After purchasing a custom jCarousel JavaScript (available at http://pastebin.com/BwsVpNjr), I encountered an issue when trying to load content with AJAX. The carousel breaks because it is unable to detect the width or height. Is there a way to have jCarous ...