Search code examples
javascriptvuexvuejs3

I'm unable to delete the todo data one by one


I created a todo app, and now I'm trying to delete the todo data one by one, but I'm getting the error stating that TypeError: Cannot read properties of undefined (reading 'id'). Don't know what to do next. I'm using the vuex concept and just help me to clear the error.

App.vue:

<template>
    <div>
        <input type="text" v-model="title">
        <button @click="onSubmit">submit</button>
        <div v-for="datas in allData" :key="datas.id">
            <h1>{{datas.title}}</h1>
            <i class="fas fa-trash-alt" @:click="deleteData(todo.id)"></i>
        </div>
    </div>
</template>
  
<script>
import { mapGetters, mapActions } from 'vuex';
export default {

    data() {
        return {
            title: ''
        }
    },
    methods: {
        ...mapActions(['fetchData', 'newData', 'deleteData']),
        onSubmit(e) {
            e.preventDefault();
            this.newData(this.title)
        },

    },

    computed: mapGetters(['allData']),
    created() {
        this.fetchData();
    }

}
</script>

index.js (store);

import axios from 'axios'
import { createStore } from 'vuex'

export default createStore({
    state: {
        todos: [],
    },
    getters: {

        allData: (state) => {
            return state.todos

        }
    },
    mutations: {
        setData: (state, todoData) => (state.todos = todoData),
        new: (state, todo) => (state.todos.unshift(todo)),
        removeData: (state, id) => state.todos = state.todos.filter((todo) => todo.id !== id),

    },
    actions: {

        async fetchData({ commit }) {
            const response = await axios.get('https://jsonplaceholder.typicode.com/todos')
            commit('setData', response.data)

        },
        async newData({ commit }, title) {
            const response = await axios.post('https://jsonplaceholder.typicode.com/todos', { title, completed: false })
            commit('new', response.data)
        },

        async deleteData({ commit }, id) {
            await axios.delete(`https://jsonplaceholder.typicode.com/todos/${id}`);
            commit('removeData', id)
        }
    }
})

Solution

  • In the template, you iterate through array and passing todo.id to delete function, why not extracted item from v-for loop dates.id?

    <template>
        <div>
            <input type="text" v-model="title">
            <button @click="onSubmit">submit</button>
            <div v-for="item of data" :key="item.id">
                <h1>{{item.title}}</h1>
                <i class="fas fa-trash-alt" @:click="deleteData(item.id)"></i>
            </div>
        </div>
    </template>
    

    And remove s in your data name because you extract one item, not items from loop.