how to get data from firestore database using vuexfire?

303 Views Asked by At

I am writing a chat app with the following data model:database image using the following approach: store/index.js

 actions: {
bindMessages: firestoreAction(({ state, bindFirestoreRef }) => {
  // return the promise returned by `bindFirestoreRef`
  return bindFirestoreRef(
    'messages',
    db.collection('groupchats')
  );
}),
},

then I access the messages store.state from my vue components like this:

computed: {
Messages() {
  return this.$store.state.messages;
},
},

according to the vuexfire docs. I was able to get the data of the whole collection (reactively) but I want the **messages array ** of a specific document assuming I know the document id. How do I do so?

1

There are 1 best solutions below

2
On BEST ANSWER

The following should do the trick:

state: {
    // ...
    doc: null
},

mutations: vuexfireMutations,

getters: {
   // ...
},

actions: {
    bindDoc: firestoreAction(({ bindFirestoreRef }) => {
        return bindFirestoreRef('doc', db.collection('groupchats').doc('MI3...'))
    })
}

You can make it dynamic as follows:

Component:

// ...
<script>
export default {
  created() {
    this.$store.dispatch('bindDoc', { id: '........' }); // Pass the desired docId, e.g. MI3...
  },
};
</script>
// ...

Vuex store:

state: {
    // ...
    doc: null
},

mutations: vuexfireMutations,

getters: {
  // ...
},
actions: {
    bindDoc: firestoreAction(({ bindFirestoreRef }, payload) => {
        return bindFirestoreRef('doc', db.collection('groupchats').doc(payload.id));
    }),
}