Why isn't the Vue component refreshing its view after the state changes in Vuex?

Recently, I delved into the world of vue and learned about its redux counterpart vuex. However, I'm facing an issue where changes in the vuex state are not triggering reactive updates to the view in a vue component.

export const store = new Vuex.Store({
    state: {
        user: {
            id: -1,
            books: []
        }
    },
    mutations: {
        ADD_BOOK(state, book) {
            state.user.books.push(book);
        }
    },
    actions: {
        addBook(context, book) {
            context.commit('ADD_BOOK', book);
        }
    },
    getters: {
        books: state => {return state.user.books}
    }
})

Within my vue component:

<template>
    <div>
        ...
        <div>
            <ul>
                <li v-for="book in books">
                    {{ book.name }}
                </li>
            </ul>
        </div>
        <div>
            <form @submit.prevent="onSubmit()">
                <div class="form-group">
                    <input type="text" v-model="name" placeholder="Enter book name">
                    <input type="text" v-model="isbn" placeholder="Enter book isbn">
                </div>
                <button type="submit">Submit</button>
            </form>
        </div>
        ...
    </div>
</template>

<script>
module.exports = {
    data () {
        return {
            isbn: ''
            name: ''
            testArr:[]
        }
    },
    methods: {
        onSubmit: function() {
            let book = {isbn: this.isbn, name: this.name};
            this.$store.dispatch('addBook', book);
            // If I do `this.testArr.push(book);` it has expected behavior.
        }
    },
    computed: {
        books () {
            return this.$store.getters.user.books;
        }
    }
}

After submitting the form data, I can see the changes reflected in both the vuex store and the component's computed property using the vuejs developer tool extension. However, the view is not updating as expected. Any insights on what might be missing here?

Answer №1

The problem lies within the computed property. It should be:

computed: {
 books () {
   return this.$store.getters.books;
 }       
}

To make things simpler, you can utilize vuex mapGetters:

import { mapGetters } from 'vuex'

export default {
  //..
  computed: {
    ...mapGetters(['books'])
  }
}

Answer №2

To accomplish this task, it is essential to pay attention

Take a look at the following illustration:

methods: {
...
},
computed: {
    books () {
        return this.$store.getters.books;
    }      
},
watch: {
    books(newVal, oldVal) {
        console.log('The value of books has changed to:' + newVal + ' from ' + oldVal)
    }
}

You can now refresh your component

<template>
    <div :key="parentKey">{{books}}</div>
</template>
data() {
    return {
        parentKey: 'first'
    }
}

Simply modify the parentKey in the watch block

watch: {
    books(newVal, oldVal) {
        this.parentKey = Math.random()
    }
}

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

Tips for collapsing all rows in an HTML table by using the Ctrl+F command

I have a table in HTML with a few rows. Check out the demo. I am looking to expand all collapsed rows when the user hits "Ctrl + F" on the keyboard. Currently, I am using the following code snippet to expand/collapse the necessary rows. $('#resultDe ...

Guide on passing mixins as properties and implementing them in child components with Vue.js

I am facing a situation where I have a parent component that contains two child components named add and edit. These components share some common properties, and I would like to utilize mixins to achieve this. To do so, I have added an object called mix to ...

Leverage PHP to dynamically populate a chart.js visualization with information sourced from an SQLite Database

I'm attempting to use chart.js to display data from an SQLite database using PHP, but I've been running into issues. Despite following multiple online tutorials, my graph remains empty or disappears altogether. This is my first time working with ...

Vue.js does not support the Elasticsearch client due to the absence of a Node.js environment

While attempting to implement the elasticsearch client in vue.js, I encountered the requirement for elasticsearch to be used within a node.js environment. Given that Vue.js does not inherently come with a node.js environment, I am seeking an alternative ...

Utilize PHP, JSON, and JavaScript to dynamically insert personalized information into HTML

Struggling, I turn to this site for help despite the dislike for "spot my mistake" code. My website urgently needs access to user-specific data from a PHP database, then convert that data into a JSON file and display it in an HTML header. The database cont ...

Enhance user interactivity by incorporating dynamic checkboxes, radio buttons, checkbox groups, and radio button groups using Ext

Hello to all the amazing folks at Stack Overflow! I've tried searching for a solution to this issue on Stack Overflow, but I couldn't find anything helpful. Here is my model: Ext.define('soru', { extend: 'Ext.data.Model' ...

Attempted to remove Child Div using Jquery, but it did not get removed as expected

Trying to remove child divs inside a parent div? There are several methods, such as: $(".ChildDiv").html(""); $('.ChildDiv > div').remove(); $(".ChildDiv").html(""); $("#ParentDiv").html(""); $(".ChildDiv div").remove(); $(".ChildDiv di ...

AngularJS tips for resolving an issue when trying to add duplicates of a string to an array

Currently dealing with a bug that occurs when attempting to push the same string into an array that has already been added. The app becomes stuck and prevents the addition of another string. How can I prevent the repeat from causing the app to get stuck w ...

The paths generated by running npm build are incorrect

After building my Vue Cli 3 project using 'npm run build', I noticed that the 'index.html' file within the new 'dist/' folder has incorrect paths, such as: <link href=/css/app.35dee36a.css <link href=/js/app.826dde09.js ...

Modal shows full JSON information instead of just a single item

This is a sample of my JSON data. I am looking to showcase the content of the clicked element in a modal window. [{ "id": 1, "companyName": "test", "image": "https://mmelektronik.com.pl/w ...

Is using $timeout still considered the most efficient method for waiting on an Angular directive template to load?

When it comes to waiting for a directive's template to render, our team has been following the approach of enclosing our DOM manipulation code in a $timeout within the directive's link function. This method was commonly used in the past, but I&ap ...

"An issue has been identified where HotTable displays an additional empty column at the start of

When utilizing HotTable with Vue3 to load an xlsx file format in a spreadsheet, an issue arises where an empty column is added at the beginning of the table. I have tried various Handsontable parameters to address this problem without success. <templ ...

404 error occurs when AngularJS removes hash symbol from URLs

I successfully eliminated the hash from my Angular JS website using the following code snippet: $locationProvider.html5Mode(true); Now, the previously displayed URL has been replaced with . The issue I'm facing is that when I do a hard refresh (Ct ...

Guide on transferring the Token from the initial response request to the header of the second request, with the help of Axios in an Ionic React application (Making 2 Post Requests

I am trying to create a user account and save the partner's data simultaneously. The initial axios request is used to create the user and obtain a token in return. I need to pass this token as a header in the second request. Despite implementing &apos ...

Unable to display the popup modal dialog on my Rails application

I currently have two models, Post and Comment. A Post has many Comments and a Comment belongs to a Post. Everything is functioning properly with the creation of posts and comments for those posts. Now, I have a new requirement where when clicking on "crea ...

Failure of app script to retrieve data from an external spreadsheet

In an attempt to consolidate data, this program aims to transfer information from one spreadsheet to another. The process involves retrieving all files within a designated folder (all of which are spreadsheets), extracting values from a specific range, and ...

Attempting to get Masonry-Layout functioning properly in Safari using imagesLoaded

I recently set up a Masonry Gallery for a WordPress site using Bootstrap 5 with 'Masonry-Layout'. Everything was working perfectly, except in Safari where the layout kept breaking. I know the solution is supposed to be 'imagesLoaded', b ...

What is the correct way to invoke a function within a JSX exported function?

Below is a snippet of code from my home.js file in a React App: function pin(){ var url = "http:myurl" axios.get(url) .then((res)=>{ if(res.data){ var txt = JSON.stringify(res.data) var lat = res.latitude var lng = ...

A guide on updating URLs that are not enclosed within an anchor tag using JavaScript

In my current scenario, I am dealing with text that includes URL links presented in two different formats. www.stackoverflow.com <a href="http://www.stackoverflow.com">Stack over flow</a> My objective is to create a straightforward function ...

One issue encountered in the AngularJS library is that the default value does not function properly in the select element when the value and

In this AngularJS example, I have created a sample for the select functionality. It is working fine when I set the default value of the select to "$scope.selectedValue = "SureshRaina";". However, when I set it to "$scope.selectedValue = "Arun";", it does n ...