11. Delete Contact

In the previous chapter, we displayed all the contacts of the logged-in user. The next thing we need to do is to allow users to delete a contact from their list.

Video tutorial:

First, you need to create a 3rd <td> tag where we will display a button to delete.

<td style="display: flex;">
	<form v-on:submit.prevent="deleteContact">
		<input type="hidden" name="email" v-bind:value="contact.email" required />
		<input type="submit" v-bind:value="isDeleting ? 'Deleting...' : 'Delete'" v-bind:isDeleting="disabled" class="btn btn-danger" />
	</form>
</td>

We have given the CSS property display: flex; because we will have another button next to it for Chat in the upcoming chapters.

After that, we create a form and attached an event listener that will be called when the form gets submitted.

Then we created a hidden input field and set its value to the contact’s email address as that will be unique.

Then we created a submit button that will display the text “Deleting…” when the AJAX is sent and “Delete” when the response is received from the server. It will also disable the button before AJAX and unable it after AJAX is finished.

Now, we need to create a Javascript method deleteContact in our methods object.

deleteContact: async function () {
	const self = this
	const form = event.target

	swal.fire({
		title: 'Are you sure?',
		text: "This will be removed from your contact",
		icon: 'warning',
		showCancelButton: true,
		confirmButtonColor: '#3085d6',
		cancelButtonColor: '#d33',
		confirmButtonText: 'Yes, delete it!'
	}).then(async function(result) {
		if (result.isConfirmed) {

			self.isDeleting = true;
			const formData = new FormData(form);

			const response = await axios.post(
				self.$apiURL + "/contact/delete",
				formData,
				{
					headers: self.$headers
				}
			);
			self.isDeleting = false;

			if (response.data.status == "success") {
				swal.fire(
					'Deleted!',
					response.data.message,
					'success'
				);

				const contactsArr = self.contacts;
				for (let a = 0; a < contactsArr.length; a++) {
					if (contactsArr[a].email == form.email.value) {
						contactsArr.splice(a, 1);
						break;
					}
				}
				self.contacts = contactsArr;
			} else {
				swal.fire("Error", response.data.message, "error");
			}
		}
	})
},

Explanation

Let’s explain what this function does.

First, it gets the current Vue JS app instance using this operator and <form> DOM instance.

Then it displays a confirmation dialog whether you really want to delete this user from your contact list or not.

delete contact confirmation
delete contact confirmation

If you confirm, then it will set the isDeleting to true so the submit button changes to “Deleting…” and it gets disabled too.

Then it will create the FormData object with the form and call an AJAX request.

If the response is received successfully, which means the contact has been deleted, then we display an alert-success message.

And finally, we remove the current contact from the local contacts array so it will be deleted from the <table> tag too.

Now, we need to create an API in Node JS that will handle this request and actually delete the user from the user’s contact list.

API to Delete Contact

Open your api/modules/contact.js file and create the following route in it:

router.post("/delete", auth, async function (request, result) {
    const email = request.fields.email;
    const user = request.user;

    const contactUser = await db.collection("users").findOne({
        $and: [{
            _id: user._id
        }, {
            "contacts.email": email
        }]
    });

    if (contactUser == null) {
        result.json({
            status: "error",
            message: "User not found."
        });
        return;
    }

    await db.collection("users").findOneAndUpdate({
        _id: user._id
    }, {
        $pull: {
            "contacts": {
                "email": email
            }
        }
    });

    result.json({
        status: "success",
        message: "Contact has been deleted."
    });
});

Here first we are getting all the values from the AJAX request. Then perform a check if that user exists in the logged-in user’s contact list.

If exists, then it will remove it from the contacts array. We are using the $pull operator to remove an element from Mongo DB, the same way we use $push to add an element in the Mongo DB array.

Test the app now and try to delete a contact. You will first be prompted for deletion, upon confirmation you will see a dialog that says that the contact has been deleted. It will be removed from <table>. And if you refresh Mongo DB Compass, you will see that it will no longer exist in that user’s contacts array.