suo
suo

Reputation: 609

VueJs - Pushing created item to existing array and having it display with the other existing items

I'm executing a POST request using Vue to insert a new record to the database. This is working as expected and the next target is to have the newly created item pushed to the existing array and have it display in a table. This is being done in a Vue component.

This is the form that is being submitted:

<form @submit.prevent="createUser">

This is the javascript part:

export default {
    data(){
        return{
            users: {},

            form: new Form({
                name: '',
                email: '',
                password: '',
                type: '',
                bio: '',
                photo: '',
            })
        }
    },
    methods:{
        displayUsers(){
            axios.get('api/user').then( ({data}) => (this.users = data) )
        },

        createUser(){
            this.form.post('api/user').then( ({ data }) => 
                 this.users.push(data.data)
            );                
        }
    },
    created() {
        this.displayUsers();                        
    }
}

From the createUser method, the entry is posted to the database and the created entry pushed to the existing users array. My backend code returns this data i.e.

return response()->json(['data' => $request->all()], 200);

Was thinking this would be enough to get the new entry to display on the table automatically without refresh as the users array has been updated but this is not happening.

The table displaying all the items looks like this:

<tr v-for="user in users" :key="user.id">
     <td>{{ user.id }}</td>
     ....

So what I'm i missing? Is there an extra step needed for my freshly created entry to be pushed automatically to my table?

Upvotes: 0

Views: 690

Answers (1)

Krantisinh
Krantisinh

Reputation: 1729

Try this -

In the createUser method, when you are assigning the newly created user, avoid mutation.

createUser(){
    this.form.post('api/user').then( ({ data }) =>{
        this.users = [ ...this.users, data.data ];
    });
}

This will help vue identify that the list has changed as we are assigning an entirely new array to users everytime a new user is created.

The push method modifies the same array. The spread operator helps avoid this mutation as we are copying all users in the new array along with newly created user.

Upvotes: 1

Related Questions