I'm attempting to utilize the same component for both adding and editing functionality in my application. Utilizing Firebase, I am checking if there is an id
in the route parameters. If there is, it should render as the edit form; otherwise, it should render the add form. However, this approach is not functioning correctly and displaying some odd behavior.
Below is the code for the ContactForm
component:
<template>
<div>
<div class="card mb-3">
<div class="card-header">{{ editing ? 'Edit' : 'Add' }} Contact</div>
<div class="card-body">
<form @submit.prevent="addContact">
<TextInputGroup
label="Name"
name="name"
placeholder="Enter your name..."
v-model="contact.name"
for="name"
/>
<TextInputGroup
type="email"
label="Email"
name="email"
placeholder="Enter your email..."
v-model="contact.email"
/>
<TextInputGroup
type="phone"
label="Phone"
name="phone"
placeholder="Enter your phone number..."
v-model="contact.phone"
/>
<input type="submit" value="Add Contact" class="btn btn-block btn-light" />
</form>
</div>
</div>
</div>
</template>
<script>
import TextInputGroup from "../layout/TextInputGroup";
import { db } from "../../firebase";
export default {
components: {
TextInputGroup
},
data() {
return {
contact: "",
editing: false,
email: "",
name: "",
phone: ""
};
},
methods: {
addContact() {
const newContact = {
name: this.name,
email: this.email,
phone: this.phone,
createdAt: new Date()
};
db.collection("contacts")
.add(newContact)
.then(docRef => {
console.log("Document written with ID: ", docRef.id);
})
.catch(error => {
console.error("Error adding document: ", error);
});
this.$router.push("/");
},
getContactById() {
db.collection("contacts")
.doc(this.$route.params.id)
.get()
.then(snapshot => {
if (!snapshot.exists) return;
this.contact = snapshot.data();
});
},
updateContact() {
const newContact = {
name: this.contact.name,
email: this.contact.email,
phone: this.contact.phone
};
db.collection("contacts")
.doc(this.$route.params.id)
.update(newContact)
.then(() => {
console.log("Updated document with ID: ");
})
.catch(function(error) {
console.error("Error updating document: ", error);
});
this.$router.push("/");
}
},
mounted() {
if ("id" in this.$route.params) {
this.getContactById();
this.editing = true;
console.log("id");
} else {
console.log("ups");
// this
}
}
};
</script>
This is the GitHub link and the live app