Monday 29 March 2021

Vue.js to Firebase - how to pass a date into Firebase

 Here are the different field types that can be excepted by Google Firebase.

> String 

> Number

> Boolean
> Map
> Array
> Null
> Timestamp

> Geopoint


Hopefully, this example will be a blueprint on how to import the other Data types too.

The documentation for the following code can be found at Timestamp  |  Firebase

The followin method in your vue.js code should work


async submit() {
if(this.$refs.form.validate()){
this.loading = true
const survey = {
title: this.title,
Date: firebase.firestore.Timestamp.fromDate(new Date()),
}
const db = await firebase.firestore();
db.collection('survey').add(survey).then(docRef => {
this.loading = false
this.snackbar = true
}).catch(error => {
console.log(error.message);
})
})
})
}
}

 

If you’re passing in your own date from a form then this is how I do this in my code.


<!-- HTML -->

<v-date-picker v-model="survey_date"
light
></v-date-picker>

<!-- CODE -->

export default {
data() {
return {
survey_date: new Date().toISOString().substr(0, 10),
snackbar: false
}
...
Date: firebase.firestore.Timestamp.fromDate(new Date(this.survey_date)),
...

 

Which works fine for me.

And bring the data back in from Firebase you’d use

this.surveys.push(
{
...
survey_date: Survey.Date.toDate(),

No comments: