Home > Net >  problem getting id and deleting document Vuejs Firestore
problem getting id and deleting document Vuejs Firestore

Time:06-30

I am creating site for my store and learning Vue js at the same time. I'm having a problem with getting product id from firestore and being able to delete product. When i create a new product in console id doesn't come out either, got this message (Document written with ID: undefined) I'm using Vue js 3 and Firebase 9

I have this on main.j

const dataBase = collection(db, "products");

and this on products.js

<script>
import { dataBase } from '../main';
import { addDoc, onSnapshot, doc, deleteDoc } from "firebase/firestore";

export default {
  name: "Products",
  props: {
    msg: String
  },
  data() {
    return {
      products: [],
      product: {
        name: '',
        detail: '',
        price: '',
        brand: '',
        category: ''
      }
    }
  },
  methods: {
    saveData() {
      try {
        const docRef = addDoc(dataBase, this.product);
        console.log("Document written with ID: ", docRef.id);
        this.reset();
      } catch (e) {
        console.error("Error adding document: ", e);
      }
    },
    reset() {
      Object.assign(this.$data, this.$options.data.apply(this));
    },
    deleteProduct(doc) {
      deleteDoc(doc(dataBase, doc.id));
    }
  },
  created() {
    onSnapshot(dataBase, (snapshot) => {
      snapshot.docs.forEach((doc) => {
        this.products.push({ ...doc.data(), id: doc.id })
      })
    });
  }
};
</script>

Thanks!

CodePudding user response:

The "Document written with ID: undefined" output is because the addDoc function is an asynchronous operation and thus returns a Promise<DocumentReference>. You'll have to either await its result, or use then:

addDoc(dataBase, this.product).then((docRef) => {
  console.log("Document written with ID: ", docRef.id);
  this.reset();
});
  • Related