The Vue component fails to refresh when the state in the store undergoes changes

Trying to create a simple todo list in Vue, but aiming to abstract everything out and utilize a dummy REST API for practice with production-level Vue projects has left my head spinning. While GET, PUT, and POST requests appear to be functioning properly, I'm struggling to understand why the list of todos doesn't automatically update when a successful POST request is made to the backend.

The TodoList component iterates through a computed property called todosFiltered() to display the todos. This computed property references the todosFiltered getter in the Vuex store. Additionally, the created() lifecycle hook is used to dispatch an action in the store that executes the initial GET request and populates an array named todos in the store upon the page's first load. The getter todosFiltered within the store returns state.todos, so I assumed that once the component re-renders, it would have the updated todos array from the state obtained via todosFiltered. However, this expected behavior is not occurring. Any insights or advice on what might be missing here are highly appreciated.

TodoList.vue

(Acknowledging that resolving the id issue is on my agenda :p)

<template>
    <div class="container">
        <input v-model="newTodo" type="text" placeholder="What must be done?" class="todo-input" @keyup.enter="addTodo">
        <transition-group name="fade" enter-active-class="animated zoomIn" leave-active-class="animated zoomOut">
            <todo-item v-for="todo in todosFiltered" :key="todo.id" :checkAll="!anyRemaining" :todo="todo"></todo-item>
        </transition-group>
        <div class="extra-container">
            <todos-filtered></todos-filtered>
        </div>
    </div>
</template>

<script>
import TodosFiltered from './TodosFiltered'
import TodoItem from './TodoItem'

export default {
  name: 'todolist',
  components: {
    TodosFiltered,
    TodoItem
  },
  data() {
    return {
        beforeEditCache: '',
        newTodo: '',
        idForTodo: 10,
    }
  },
  // Methods
  methods: {
    addTodo() {
        if (this.newTodo.trim().length == 0) {
            return
        }
        this.$store.dispatch('addTodo', {
            id: this.idForTodo,
            title: this.newTodo,
            completed: false
        })
        this.newTodo = ''
        this.idForTodo++
    }
  },
  computed: {
    todosFiltered() {
        return this.$store.getters.todosFiltered
    },
  },
  created() {
    this.$store.dispatch('loadTodos')
  },
}
</script>

store.js

export const store = new Vuex.Store({
    state: {
        filter: 'all',
        todos: []
    },
    getters: {
        todosFiltered(state) {
            if (state.filter == 'all') {
                return state.todos
            } else if (state.filter == 'active') {
                return state.todos.filter(todo => !todo.completed)
            } else if (state.filter == 'completed') {
                return state.todos.filter(todo => todo.completed)
            }
            return state.todos
        },
        showClearCompleted(state) {
            return state.todos.filter(todo => todo.completed).length > 0
        }
    },
    mutations: {
        addTodo(state, todo) {
            state.todos.push(todo)
        },
        setTodos(state, todos) {
            state.todos = todos
        },
    },
    actions: {
        loadTodos(context) {
            axios.get('http://localhost:3000/todos')
            .then(r => r.data)
            .then(todos => {
                context.commit('setTodos', todos)
            })
        },
        updateTodo(context, todo) {
            axios.put('http://localhost:3000/todos/' + todo.id, {
                "id": todo.id,
                "title": todo.title,
                "completed": todo.completed
            })
        },
        addTodo(context, todo) {
            axios.post('http://localhost:3000/todos', {
                "id": todo.id,
                "title": todo.title,
                "completed": todo.completed
            })
            .then(todo => {
                context.commit('addTodo', todo)
            })
        },
    }
})

In Vue Dev Tools, upon adding a todo, todos in the store's state is promptly updated, and the todosFiltered computed property in the TodoList component also mirrors this change. However, the new todo fails to appear in the list, presenting a peculiar situation.

Answer №1

One effective solution is to implement a method known as refresh().

In essence, you maintain a local list of todos within your data() method. The refresh() method loads all the todos from the store into this local list. Whenever an action like creating, deleting, or updating occurs, invoking the refresh method re-loads the list.

In your TodoList.vue:

<template>
    <todo-item v-for="todo in todosFiltered" :key="todo.id"></todo-item>
</template>

<script>
export default {
    data() {
        return {
            // Local storage for Todos 
            todosFiltered: []
        }
    },
    methods {
        refresh() {
            // Retrieve todo list from the store
            this.todosFiltered = this.$store.getters.todosFiltered;
        },
        addTodo() {
            this.$store.dispatch('addTodo').then(() => {
                // Refresh after adding a new Todo
                this.refresh();
            })
        },
        updateTodo() {
            this.$store.dispatch('updateTodo').then(() => {
                // Refresh after updating a Todo
                this.refresh();
            })
        },
        deleteTodo() {
            this.$store.dispatch('deleteTodo').then(() => {
                // Refresh after deleting a Todo
                this.refresh();
            })
        }
    },
    created() {
        this.$store.dispatch('loadTodos').then( () => {
            // Initial refresh after loading Todos saved in Vuex
            this.refresh();
        })
    }
}
</script>

Instead of replacing your existing code, incorporate these principles into it.

Answer №2

One issue that arises is the utilization of a $store.getter within a v-for loop. Here are some steps to address this problem:

  1. Define your computed property as follows:

    todos() { return this.$store.todos; }

  2. Modify your v-for loop to iterate through todo in todos

  3. Include a v-if statement in the loop like v-if="filtered(todo)"
  4. Develop a new function named filtered (or any other name you prefer), and incorporate your "filteredTodos" logic there, returning true or false when necessary
  5. If you wish to reuse this code, utilize a mixin to share it across different components

I hope these instructions help resolve the issue for you

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

Implementing Material-UI’s FlatButton and Dialog in ReactJS for dynamic TableRow functionality

I am working with Material-UI and have implemented a <Table> component. Each dynamically rendered <TableRow> in the <TableBody> needs to include a button (<FlatButton>) within one of the columns. When this button is clicked, a <D ...

Dynamic Binding of Checkboxes in Vuex

I am encountering a problem with binding checkboxes using Vuex. Even though I am using v-model with a variable that has a getter and setter to set or get the value in the store, I keep getting incorrect data in the store. The issue arises when I click on a ...

Experiencing difficulty in updating GitHub pages with React application

Looking for help updating my deployed active react app on GitHub pages with newer code, such as color changes and text updates. The updated code has been pushed to the main branch of my GitHub repo but the live GitHub page is not reflecting the changes. De ...

Calculate the total number of blank input boxes within a specific row of the table

What is the method to count the number of input boxes without a value in a table row using jquery? For instance: <table id="table1"> <tr class="data" id="row5"> <td><input type="text" value="20%" /></td> <td><input ...

Sass is throwing an error message saying 'Module not found' during the compilation process

After installing sass using npm ($npm install sass), I attempted to create a JSON script. Unfortunately, when running it, I encountered an error stating 'Cannot find module'. ...

Troubleshooting the issue with Protractor/Jasmine test when browser.isElementPresent does not detect a class in the

As a newcomer to Jasmine testing, I've been facing some challenges while running my tests. Specifically, I have been struggling with my webdriver closing the browser before it can check the '.detailsColumn' element for expected results. Afte ...

Generating a dynamic form by utilizing a JavaScript JSON object

I need assistance with creating an html form based on a JSON object’s properties. How can I target multiple levels to generate different fields and also drill down deeper to access field details? I am open to suggestions for alternative formats as well. ...

Tips for dynamically populating JSON data using a dropdown selection?

I am currently exploring HTML forms as a new web developer. I have been experimenting with displaying JSON data in a div based on a selection from a dropdown menu using jQuery in Chrome. However, my code does not seem to be functioning properly. Even tho ...

The combination of sass-loader and Webpack fails to produce CSS output

Need help with setting up sass-loader to compile SCSS into CSS and include it in an HTML file using express.js, alongside react-hot-loader. Check out my configuration file below: var webpack = require('webpack'); var ExtractTextPlugin = require ...

Is there a way to create a navigation menu that highlights as we scroll down the page?

Check out this example of what I am looking for. https://i.stack.imgur.com/fdzvZ.png If you scroll, you will notice that the left menu highlights. Sub-menus will extend when the corresponding menu is highlighted and collapse when other menus are highlig ...

Steps to display a NotFound page when the entered path does not match the route in module federation React micro frontends

Typically, if the provided path does not match, we display the NotFound page to the user using the following code snippet <Route path={"*"} component={NotFound} /> However, upon adding this code, I always get redirected to the home page ( ...

Converting an Angular1 App into a VueJs app: A step-by-step guide

Let's dive right in: I'm embarking on the journey of revamping an app that originally utilized Angular 1, but this time around I'll be harnessing the power of VueJS 2. As someone unfamiliar with Angular 1, I'm faced with some perplexing ...

Is there a method to accurately detect the rendering of individual elements within a React Component, rather than the entire component itself?

While it's known that Components rendering can be detected through React's Developer Tool, I came across other methods in this source. However, what I'm specifically interested in is detecting the rendering of individual elements within a Co ...

Vue router beforeRouteEnter - when the page is refreshed, the button label vanishes

<script> export default { name: 'TEST', data() { return { prevRoute: '' } }, methods: { goBack() { return this.$router.go(-1); }, }, beforeRouteEnter(to, from, next) { next(vm => { ...

In search of the mean value using PHP, jQuery, and AJAX technologies

I have successfully created a star rating system using PHP and jQuery. The issue arises when attempting to display the average rate for a specific item that I am rating; instead, the average value printed is for all items being rated. Here is my jQuery co ...

Encountering a lack of data in the request body when posting in Express.js

Here are my two attached files. I am encountering an empty response from req.body. Index.html file: <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQ ...

Issue encountered when upgrading from Angular 4 to Angular 5: Module '@angular/router' is not found

I recently made the switch from angular 2 to angular 5. However, after the upgrade, I encountered some errors in my ts file. Should I remove @angular/core and @angular/router in angular 5? Here is a snippet of my package.json post-upgrade. Below are the de ...

Steps for incorporating a variable into a hyperlink

I'm trying to achieve something similar to this: var myname = req.session.name; <------- dynamic <a href="/upload?name=" + myname class="btn btn-info btn-md"> However, I am facing issues with making it work. How can I properly ...

Pressing the ENTER key does not submit the text box data in Rails/Bootstrap, but clicking the SUBMIT button does

I need assistance with my Rails 4 and Bootstrap 3 project. I have implemented an email address field on my page (localhost:3000) where users can enter their email and click the SUBMIT button to send it to the MongoDB database. However, pressing the ENTER k ...

Refresh the data list displayed within a specified div container

On my jsp page, I initially populate a model attribute with some data. Then, I use the following code to display this list on the jsp page: <c:forEach var="pattern" items="${patterns}"> <li class="list-group-item liitem"><st ...