Home > Mobile >  Not able to remove a user from a table
Not able to remove a user from a table

Time:10-09

I have a nested table where I'm grouping users by the department that they belong to. The issue I'm having is that if I click on the delete button, that specific user that I've deleted isn't being removed from the list and I'm not getting any errors in my console.

Here is my code

<template>
    <div>
        <div class="row">
            <div class="col-lg-12">
                <table class="table table-bordered table-sm">
                    <thead>
                        <tr>
                            <th>Name</th>
                            <th>Job Title</th>
                        </tr>
                    </thead>

                    <tbody v-for="(users, department) in personnal">
                        <tr>
                            <td>{{ department }}</td>
                        </tr>

                        <tr v-for="user in users">
                            <td>{{ user.name }}</td>
                            <td>{{ user.job_title }}</td>
                            <td>
                                <div class="btn btn-danger btn-sm" @click="removeUser(user)">
                                    <i class="fa fa-trash"></i>
                                </div>
                            </td>
                        </tr>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</template>

export default
{
    props: [],
    data() {
        return {
            personnal: {},
        }
    },
    computed: {

    },
    methods: {
        getUsers(){
            axios.get(`/api/users`).then(response => {
                this.personnal = response.data.users;
            });
        },
        removeUser(user){
            axios.delete(`/api/users/${user.id}/delete`).then(response => {
                Object.keys(this.personnal).forEach(user => {
                    this.personnal[user].filter(u => u.id !== response.data.id);
                    this.personnal[user].slice(response.data);
                });
            });
        }
    },
    mounted() {
        this.getUsers();
    }
}
</script>

CodePudding user response:

First of all, you have to pass both department and user in the click event:

<div class="btn btn-danger btn-sm" @click="removeUser(department, user)">
    <i class="fa fa-trash"></i>
</div>

Then, in the removeUser method:

removeUser(department, user){
    axios.delete(`/api/users/${user.id}/delete`).then(response => {
        const index = this.personnal[department].findIndex(u => u.id === user.id);
        this.personnal[department].splice(index, 1);
    });
}
  • Related