javascriptvue.jsvuefire

Access method in the firestore section - vuefire


Am trying to access a method in the firestore section of vuefire , but am getting this error :

vue-router.esm.js?8c4f:2257 TypeError: Cannot read property 'messagesWith' of undefined
    at eval (Chat.vue?62f3:214)

This is the line where the error occurs :

parents: this.messagesWith(db.auth().currentUser.uid),

Below is my full code :

export default {
  data: () => ({

    activeChat: undefined,
    parents: [],
    messages: [],
    messageForm: {
      content: "",
      me: true,
      createdAt: new Date()
    }
  }),
  firestore: {
    // eslint-disable-next-line no-undef
    messages: db.collection(message_collection_name).orderBy('createdAt','asc'),
    parents: this.messagesWith(db.auth().currentUser.uid),
  },
  computed: {
    
  },
  methods:{
    
    dmCollection(toUid){
      const idPair = [db.auth().currentUser.uid, toUid].join('_').sort();
      return db.firestore().collection(direct_message).doc(idPair).collection(message_collection_name);
    },
    sendDm(toUid, messageText){
      return this.dmCollection(toUid).add({
        from: db.auth().currentUser.uid,
        message: messageText,
        sent: db.firestore.FieldValue.serverTimestamp()
      })
    },
    messagesWith(uid){
      return this.dmCollection(uid).orderBy('sent', 'desc').get();
    },
    
  },
}

Solution

  • In order to access the local options/methods define firestore as a function that returns an object :

      firestore:()=> ({
        // eslint-disable-next-line no-undef
        messages: db.collection(message_collection_name).orderBy('createdAt','asc'),
        parents: this.messagesWith(db.auth().currentUser.uid),
      }),