Using Firebase in a Vue App with Vuexfire — Add Document and Current Timestamp
Tags: javascript, webdev, programming, java
Published: 2021-01-26 01:24:34

**Check out my books on Amazon at https://www.amazon.com/John-Au-Yeung/e/B08FT5NT62**

**Subscribe to my email list now at http://jauyeung.net/subscribe/**


The Vuefire library lets us add Firebase database manipulation capabilities right from our Vue app.

In this article, we’ll look at how to use Vuefire and Vuexfire to add support for Cloud Firestore database manipulation into our Vue app.

### Adding Documents to a Collection

We can add a document to a collection with the `add` method.

For example, we can write:

`db.js`

```
import firebase from "firebase/app";
import "firebase/firestore";
export const db = firebase
  .initializeApp({ projectId: "project-id" })
  .firestore();
const { Timestamp, GeoPoint } = firebase.firestore;
export { Timestamp, GeoPoint };
```

`main.js`

```
import Vue from "vue";
import App from "./App.vue";
import { firestorePlugin } from "vuefire";
import { vuexfireMutations, firestoreAction } from "vuexfire";
import Vuex from "vuex";
import { db } from "./db";
Vue.use(Vuex);
Vue.use(firestorePlugin);
Vue.config.productionTip = false;
const store = new Vuex.Store({
  state: {
    books: []
  },
  mutations: {
    ...vuexfireMutations
  },
  actions: {
    bindBooksRef: firestoreAction((context) => {
      return context.bindFirestoreRef(
        "books",
        db.collection("books").orderBy("title", "desc")
      );
    }),
    addBook: firestoreAction(async ({ state }, book) => {
      await db.collection("books").add(book);
      console.log("book added");
    })
  },
  getters: {
    books: (state) => {
      return state.books;
    }
  }
});
new Vue({
  store,
  render: (h) => h(App)
}).$mount("#app");
```

`App.vue`

```
<template>
  <div>
    <button @click="addBook">add book</button>
    <div>{{books}}</div>
  </div>
</template>
<script>
import { mapGetters, mapActions } from "vuex";
export default {
  data() {
    return {};
  },
  methods: {
    ...mapActions(["bindBooksRef"]),
    addBook() {
      this.$store.dispatch("addBook", { title: "qux" });
    }
  },
  computed: {
    ...mapGetters(["books"])
  },
  mounted() {
    this.bindBooksRef();
  }
};
</script>
```

We have the `bindBookRef` action to sync the Firebase `books` collection with the `books` state.

Also, we have the `addBook` action which calls `add` to add our `book` object into the `books` collection.

Then in `App.vue` , we call `this.$store.dispatch` method to dispatch the `addBook` action with the object we want to add.

The button runs the `addBook` method when we click it.

So when we click it, then the entry is added.

### Current Timestamp

We can add the current timestamp at creation or update.

To do that, we can use the `firebase.firestore.FieldValue.serverTimestamp` method.

For example, we can write:

`App.vue`

```
<template>
  <div>
    <button @click="addBook">add book</button>
    <div>{{books}}</div>
  </div>
</template>
<script>
import { mapGetters, mapActions } from "vuex";
import firebase from "firebase/app";

export default {
  data() {
    return {};
  },
  methods: {
    ...mapActions(["bindBooksRef"]),
    addBook() {
      this.$store.dispatch("addBook", {
        title: "qux",
        createdAt: firebase.firestore.FieldValue.serverTimestamp()
      });
    }
  },
  computed: {
    ...mapGetters(["books"])
  },
  mounted() {
    this.bindBooksRef();
  }
};
</script>
```

We just use it anywhere we want to add a timestamp.

Then we get something like:

```
{ "createdAt": { "seconds": 1598895154, "nanoseconds": 675000000 }, "title": "qux" }
```

added to the `books` collection.

### Conclusion

Vuexfire provides us with methods to add documents and current timestamps with our Vue app and Firebase.