Issue with Vuex getter not reflecting correct value after modifying an array

I've been delving into the world of vuex, and I'm currently working on fetching the count or an array when I make additions or removals. Below, you'll find the code snippets I'm working with.

home.vue template

<template>
    <div :class="page.class" :id="page.id">
        <h3>{{ content }}</h3>
        <hr>
        <p>Registered users count {{ unRegisteredUserCount }}</p>
        <ul class="list-unstyled" v-if="getUnRegisteredUsers">
            <li v-for="(unregistereduser, n) in getUnRegisteredUsers" @click="register(unregistereduser)">
                {{ n + 1 }}
                - {{ unregistereduser.id }} 
                {{ unregistereduser.fname }} 
                {{ unregistereduser.lname }}
            </li>
        </ul>
        <hr>
        <p>Registered users count {{ registeredUserCount }}</p>
        <ul class="list-unstyled">
            <li v-for="(registereduser, n) in getRegisteredUsers" @click="unregister(registereduser)">
                {{ n + 1 }}
                - {{ registereduser.id }} 
                {{ registereduser.fname }} 
                {{ registereduser.lname }}
            </li>
        </ul>
    </div>
</template>

<script>
    export default {
        name: 'home',
        data () {
            return {
                page: {
                    class: 'home',
                    id: 'home'
                },
                content: 'This is home page'
            }
        },
        computed: {
            getUnRegisteredUsers() {
                if( this.$store.getters.getCountUnregisteredUsers ) {
                    return this.$store.getters.getAllUnRegisteredUsers;
                }
            },
            getRegisteredUsers() {
                if( this.$store.getters.getCountRegisteredUsers > 0) {
                    return this.$store.getters.getAllRegisteredUsers;
                }
            },
            unRegisteredUserCount() {
                return  this.$store.getters.getCountUnregisteredUsers;
            },
            registeredUserCount() {
                return  this.$store.getters.getCountRegisteredUsers;
            }
        },
        methods: {
            register(unregistereduser) {
                this.$store.commit({
                    type: 'registerUser', 
                    userId: unregistereduser.id
                });
            },
            unregister(registereduser) {
                this.$store.commit({
                    type: 'unRegisterUser', 
                    userId: registereduser.id
                });
            }
        },
        mounted: function() {

        }
    }
</script>

state.js

export default {
    unRegisteredUsers: [
        {
            id: 1001,
            fname: 'John',
            lname: 'Doe',
            state: 'Los Angeles',
            registered: false
        },
        {
            id: 2001,
            fname: 'Miggs',
            lname: 'Ollesen',
            state: 'Oklahoma',
            registered: false
        },
        {
            id: 3001,
            fname: 'Zoe',
            lname: 'Mcaddo',
            state: 'New York',
            registered: false
        },
        {
            id: 4001,
            fname: 'Jane',
            lname: 'Roberts',
            state: 'Philadelphia',
            registered: false
        },
        {
            id: 5001,
            fname: 'Ellen',
            lname: 'Jennings',
            state: 'Houston',
            registered: false
        },
        {
            id: 6001,
            fname: 'Joseph',
            lname: 'Reed',
            state: 'Boston',
            registered: false
        },
        {
            id: 7001,
            fname: 'Jake',
            lname: 'Doe',
            state: 'Portland',
            registered: false
        }
    ],
    registeredUsers: []
}

getters.js

export default {
    getAllUnRegisteredUsers(state) {
        return state.unRegisteredUsers;
    },
    getAllRegisteredUsers(state) {
        return state.registeredUsers;
    },
    getCountUnregisteredUsers(state) {
        return state.unRegisteredUsers.length;
    },
    getCountRegisteredUsers(state) {
        return state.registeredUsers.length;
    },
    getUserById(state) {

    }
}

mutations.js

export default {
    registerUser(state, payload) {
        //find user
        const user = _.find(state.unRegisteredUsers, {
            'id': payload.userId
        });

        // remove user from original array
        _.remove(state.unRegisteredUsers, {
            'id': payload.userId
        });

        // set user object key value
        user.registered = 'true';

        // add user to new array
        state.registeredUsers.push(user);

        console.log(state.registeredUsers.length + ' - registered users count');
    },
    unRegisterUser(state, payload) {
        //find user
        const user = _.find(state.registeredUsers, {
            'id': payload.userId
        });

        // remove user from original array
        _.remove(state.registeredUsers, {
            'id': payload.userId
        });

        // set user object key value
        user.registered = 'false';

        // add user to new array
        state.unRegisteredUsers.push(user);

        console.log(state.unRegisteredUsers.length + ' - unregistered users count');
    }
}

Although on page load the array count renders correctly, the count does not update when I remove values from registeredUsers and unRegisteredUsers. What am I overlooking here? Could someone kindly explain and advise on how I can achieve the correct count? Thank you

Answer №2

The issue lies in the fact that you are modifying an array directly. It's best practice to avoid mutating arrays as it can lead to reactivity issues and make troubleshooting a nightmare.

To maintain reactivity, replace a value with a new array by using functions like _.filter or _.reject as shown in the code snippet below.

state.registeredUsers = _.reject(state.registeredUsers, {
    'id': payload.userId
});

Contrary to another suggestion by choasia, Lodash is not the root of the problem. In fact, Lodash can be quite helpful when used correctly with Vuejs. Just remember to use functions that explicitly return a new array. Refer to the Lodash documentation under "returns" to understand what each function returns.

Answer №3

When it comes to modifying a list or an object in vuejs (as well as vuex), it can be quite challenging due to the constraints of JavaScript.
If you find yourself using lodash to delete items in an array, be aware that this can lead to conflicts with vuejs's reactivity. For more information on this issue, you can refer to this thread.
In order to safely remove an item from an array, it is recommended to utilize the splice method.

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

Building a visual bubble representation with Reactjs and D3

I am currently encountering an issue while attempting to create a bubble chart using React + D3. Although there are npm modules available for this solution, I am unable to implement them in the project I am working on. Moreover, the lack of examples demons ...

Having trouble with the auto import feature for Nuxtjs components?

I encountered an issue with my Vue file when trying to automatically import components into my view. The documentation suggests that I just need to set the components to true in the nuxt.config.js file. I attempted this, but it did not work. Am I importing ...

Having trouble making event listeners work with React useState in Next.js?

I'm currently working on a webpage where I want to have a fixed hamburger icon in the top-right corner that, when clicked, opens a navbar. The navbar should close if the user clicks outside of it, and the hamburger icon should reappear. Since Next.js ...

Challenges of performance in EmberJS and Rails 4 API

My EmberJS application is connected to a Rails 4 REST API. While the application is generally working fine, it has started to slow down due to the nature of the queries being made. Currently, the API response looks like this: "projects": [{ "id": 1, ...

Enhancing jquery datatable functionality with data-* attributes

I successfully added an id to each row of my data table using the rowId property, as outlined in the documentation. $('#myTable').DataTable( { ajax: '/api/staff', rowId: 'staffId' } ); Now I am wondering how I can ad ...

Displaying elements above my React sidebar

I am working on developing a Login application with a landing page using React Router and Redux. In order to have a Sidebar that is always present in all the components within the application, I have setup the Sidebar component as a route that is constantl ...

Displaying JSON data received from an AJAX request on the screen

Our server is located in Europe. Occasionally, a user based in America reports an issue when using the $.getJSON function. Instead of passing the JSON response to JavaScript, the user's browser simply displays it. The AJAX call appears as follows: ...

Bidirectional Communication between ExpressJS and Mongoose Models

Let's consider a scenario where we have a User model and a Book model in our express app, both referencing each other. How can mongoose middleware be utilized to ensure that both models stay synchronized when saving either one? It would be beneficial ...

Jquery code not responding to ajax callback

i have the following two functions defined: function populateTableData(){ jQuery('select[name="drg-select"]').change(function() { drgValue=jQuery(this).val(); url="http://localhost/ur ...

My website code being stored in cache by Chrome (as well as other browsers)

Issue: I am facing an issue with hosting a widget on my client's website where the widget needs to be different for each page. To display the widget, the client embeds a script tag on their pages. This script is loaded on every page and the content ...

Tips for toggling the visibility of a <div> element with a click event, even when there is already a click event assigned

No matter what I try, nothing seems to be working for me. I'm looking to hide the <div id="disqus_thread"> at first and then reveal it when I click on the link "commenting", after the comments have loaded. This particular link is located at the ...

I am seeking assistance with generating a printed list from the database

Struggling for two full days to successfully print a simple list from the database. Take a look at the current state of the code: function CategoriesTable() { const [isLoading, setLoading] = useState(true); let item_list = []; let print_list; useEffect(( ...

Obtain the breakpoint value from Bootstrap 5

We have recently updated our project from Bootstrap 4 to Bootstrap 5. I am trying to retrieve the value of a breakpoint in my TypeScript/JavaScript code, which used to work in Bootstrap 4 with: window .getComputedStyle(document.documentElement) .g ...

Fetch data using Ajax without the need for a hash signal

My current goal is to load content through Ajax on a website. Let's say our main page is example.com/blankpage (I've eliminated the .html extension using htaccess). At the moment, I have it set up so that when a link on the page directs to mysite ...

How can I retrieve Json array data in android studio using volley?

Here is a JSON encoded array provided below:- { "imager": [{ "title": "Guru", "images": ["images\/6.png", "images\/androidIntro.png", "images\/barretr_Earth.png"] }] } The issue at hand is that I need to extract each image from th ...

I'm puzzled by the inconsistency of my scrolltop function on mobile, as it seems to be scrolling to various parts of the page depending on my

I am encountering an issue with a function that scrolls to a specific element when a button is clicked. Strangely, this functionality works fine on desktop but fails on mobile devices. It successfully scrolls to the correct position only when at the top of ...

Restricting form choices for multi-level child inputs using JavaScript

In my current form, the structure is as follows: kingdom --> phylum --> class --> order --> family --> genus... If the kingdom = Animalia, then the options for phylum should be a specific list. Similarly, if the phylum is set to Chordata, ...

Issue with retrieving URL parameters in Nextjs during server side rendering

Currently, I'm attempting to extract the request query, also known as GET parameters, from the URL in server-side rendering for validation and authentication purposes, such as with a Shopify shop. However, I am facing issues with verifying or parsing ...

Converting SQL database tables into MVC webpages using JavaScript

Currently, I am working on populating an MVC webpage by utilizing a Controller and a View using C#, HTML, and Javascript exclusively. It is crucial that I avoid using a model or PHP due to the existing format in use. Thus far, all the data has been succes ...

AngularJS fails to prioritize the following element

Here is my HTML code: <div ng-app="app"> <form> <div class="form-group"> <label >Username</label> <input focus type="text" class="form-control" id="loginUserName" ng-model="userForm.crn" required/> ...