Recently started learning Vue.js and Firestore, facing a challenge with what should be a simple task.
1) I am trying to fetch default values from an existing template document in my Firestore database.
2) The goal is to use these default values to create a new record in a different collection.
I am able to successfully retrieve the default values from the template document and they are displayed correctly when using console.log. So, I expect that the variables starting with "this." now contain the correct values for creating a new document, right?
However, when I try to add a new document using these default values, the newly created document in 'nodes' collection contains blank strings instead of the values retrieved from the initial query. The fields are present but empty ("").
The function createNewLocation() is triggered by a button press on the page. While the function works, it fails to copy over the values as expected.
I have attempted various approaches without success. Could this issue be due to latency where the first query hasn't completed before the new document is created? If so, how can I overcome this obstacle?
Thank you.
<script>
import db from '../components/firebaseInit'
export default {
name: 'loc-new',
data () {
return {
//Values entered in the form
new_loc_id: null,
new_loc_name: null,
//Default values placeholders used in location creation
node_hw_ver: 0,
node_sw_ver: 0,
node_user_descr: '',
node_user_name: '',
node_type_class: '',
node_type_id: 0,
}
},
methods: {
createNewLocation () {
//retrieve template /templates/(nodes)/node_templates/
db.collection('templates').doc('nodes').collection('node_templates')
.where('use_for_new', '==', true).get().then((querySnapshot) => {
querySnapshot.forEach((doc) => {
this.node_hw_ver = doc.data().default_hw_ver
console.log("hw ", this.node_hw_ver)
this.node_sw_ver = doc.data().default_sw_ver
console.log("sw ", this.node_sw_ver)
this.node_user_descr = doc.data().default_user_descr
console.log("descr ", this.node_user_descr)
this.node_user_name = doc.data().default_user_name
console.log("name ", this.node_user_name)
this.node_type_class = doc.data().type_class
console.log("class ", this.node_type_class)
this.node_type_id = doc.data().type_id
console.log("id ", this.node_type_id)
})
})
db.collection('nodes').add({
loc_id: this.new_loc_id,
addr: 1,
user_name: this.node_user_name,
user_descr: this.node_user_descr,
type_id: this.node_type_id,
type_class: this.node_type_class
})
.then(function(docRef){
//do nothing
})
.catch(function(error){
console.error("Error adding node document: ", error)
return null
})
}
}
}
</script>