How to resolve Firestore promise directly to a Vue reactive() proxy?

Viewed 115

Using Vue 3/Typescript, how do I resolve a FireStore promise resulting in an array of objects, to a reactive proxy object using map()?

In this instance, I do not wish to use forEach() or Vuex.

setup(){
   ...
   const clients = reactive(
       db
           .collection('users')
           .orderBy('name', 'asc')
           .get()
           .then(snapshot =>
               snapshot.docs.map(doc => ({
                   id: doc.id,
                   name: doc.data().name,
               }))
           )
   )
   ...
}

console.log()

Promise { <state>: "pending" }
    <state>: "fulfilled"
    <value>: Array [ {…} ]
1 Answers

Init your reactive property by an empty array then mutate inside the onMounted hook :

setup(){
   ...
   const state = reactive({
     clients:[]
   })

onMounted(()=>{
  db.collection('users')
           .orderBy('name', 'asc')
           .get()
           .then(snapshot =>{
             state.clients=  snapshot.docs.map(doc => ({
                   id: doc.id,
                   name: doc.data().name,
               }))
           
            })

})
   ...

}
Related