Home > OS >  attempting to delete one to-do but instead all to-do's are getting deleted Vue 2 with Vuex 3
attempting to delete one to-do but instead all to-do's are getting deleted Vue 2 with Vuex 3

Time:07-22

I'm using Vuex to make a simple to-do app however when I try to delete one to-do all the todos are getting deleted, I want to understand why all of them are getting deleted even though I only delete the one that matches the id of the to-do I want to delete.

vue devtools is showing that I am sending only the id I want to delete, I think the problem is with the mutation: deleteTodo however I could not catch the mistake I have made

This is the code:

todoList.vue : 

<template>
    <div>
        <h1>
            Todo List
        </h1>
        <ul v-for="todo in todos" :key="todo.id">
            <li>
                <p>title : {{ todo.title }}</p>
                <p>Body : {{ todo.body }}</p>
                <span>Id : {{ todo.id }}</span>
                <button @click="deleteTodo(todo.id)">Delete</button>
            </li>
        </ul>
    </div>
</template>
<script>

export default {
    methods: {
        deleteTodo(id) {
            this.$store.dispatch("deleteTodo", id)
        }
    },
    computed: {
        todos() {
            return this.$store.getters.getTodos
        }
    }
}
</script>
<style>
</style>

store.js file 

import Vue from "vue";
import Vuex from "vuex";

Vue.use(Vuex);

const store = new Vuex.Store({
  state: {
    todos: [],
  },
  getters: {
    getTodos: (state) => {
      return state.todos;
    },
  },
  mutations: {
    addTodo: (state, newTodo) => {
      const generatedId = state.todos.length   1;
      state.todos = [
        ...state.todos,
        { id: generatedId, title: newTodo.title, body: newTodo.body },
      ];
    },
    deleteTodo: (state, id) => {
      state.todos = state.todos.filter((todo) => {
        todo.id != id;
      });
      return state.todos;
    },
  },
  actions: {
    addTodo: (context, newTodo) => {
      context.commit("addTodo", newTodo);
    },
    deleteTodo: (context, id) => {
      context.commit("deleteTodo", id);
    },
  },
});
export default store;

CodePudding user response:

The v-for should be used in li element not the ul :

<ul>
    <li v-for="todo in todos" :key="todo.id">
        <p>title : {{ todo.title }}</p>
        <p>Body : {{ todo.body }}</p>
        <span>Id : {{ todo.id }}</span>
        <button @click="deleteTodo(todo.id)">Delete</button>
    </li>
</ul>

and you should add return in the filter function return todo.id != id;:

  deleteTodo: (state, id) => {
      state.todos = state.todos.filter((todo) => {
        return todo.id != id;
      });
      return state.todos;
    },
  • Related