Using Vue.js and Firebase I am build the simplest CRUD I can think of.
When I 'create' data from a form I can send it to the database but when I try to update my local array of objects there is no document id, as this is created by firebase when I create a new document. So how can I retrieve the new document id without having to get all the data from the database?
There must be a pattern for this. The only thing I can think of doing is getting 'all' the data from the database again. But is there an easier way?
Is there a way to get the id passed back to the component of a newly created document?
Here is my component with only the necessary bits,
<template lang="html">
<div class="crud">
<h1>I am the crud component</h1>
<div v-for="item in peoples" :key="peoples.id" class="peoples">
<h3>name: {{ item.name}} age: {{ item.age}} id: {{ item.id }} <button @click="deletePeople(item.id)">delete</button> </h3>
</div>
<form @submit.prevent="addPerson()">
<div>
<label for="name">Name:</label>
<input type="text" name="name" v-model="name">
</div>
<div>
<label for="age">Age:</label>
<input type="number" name="age" v-model="age">
</div>
<div>
<button>add person to database</button>
</div>
</form>
</div>
</template>
<script>
import db from '@/firebase/init'
export default {
name: 'Crud',
data(){
return {
msg: 'hello all',
peoples: [],
name: null,
age: null
}
},
methods:{
addPerson(){
console.log('addPerson() method running');
console.log('person: ' + this.name);
db.collection('people').add({
name: this.name,
age: this.age
}).then(() => {
db.collection('people').get().then(snapshot => {
this.peoples = []
snapshot.forEach(doc => {
// console.log(doc.data(), doc.id);
let people = doc.data()
people.id = doc.id
this.peoples.push(people)
})
})
// console.log('push to local data');
// this.peoples.push({ name: this.name, age: this.age})
})
},
Any help would be greatly appreciated,
Thanks