I am trying to return user collection from Firebase/Firestore but the code I have does not return anything when I check it in the console. Can you please help me, I am new to Vue? I am trying to find the user which has the same display name as the one currently logged in but I am stuck.
<template>
<p>Process Payroll</p>
<h1>{{ user.displayName }} </h1>
<h1>{{ docs }} </h1>
</template>
<script>
import getUser from '@/composables/getUser'
import { ref } from 'vue'
import { projectFirestore } from '../firebase/config'
export default {
setup(){
const { user } = getUser()
const lastName = ref('')
const firstName = ref('')
const docs = ref('')
const returnUser = async () => {
const res = await projectFirestore.collection('users').get()
if (!error.value) {
console.log(res.docs)
const doc = res.docs.filter((user1) =>{
if (user1.displayName == user.displayName){
return user.lastName
}
})
docs.value = doc
}
}
return {user, docs, returnUser }
}
}
</script>
<style>
</style>
CodePudding user response:
Firstly, the condition that you have applied on the filter
function needs to be changed so that the variables are not mixed up. Currently, you were comparing the element's displayName
with itself which will always be true.
Secondly, you can query the document that's required from the collection with simple query. More information can be found here.
Also, before jumping to the next conclusion, check the response that is returned from firestore
. The get()
method from firestore
returns you a querySnapshot
so there's no need to call res.docs
. You will get your documents directly in res
which will be an array. Just iterate over it to get a single document, whose properties can then be easily accessed using .data()
method
Solution
<template>
<p>Process Payroll</p>
<h1>{{ user.displayName }} </h1>
<h1>{{ docs }} </h1>
</template>
import getUser from "@/composables/getUser";
import { ref } from "vue";
import { projectFirestore } from "../firebase/config";
export default {
setup() {
const { user } = getUser();
const lastName = ref("");
const firstName = ref("");
const docs = ref([]);
const returnUser = async () => {
const res = await projectFirestore
.collection("users")
.where("displayName", "==", user.displayName)
.get();
if (!error.value) {
// check your response here.
console.log(res);
const doc = res.filter((userObj) => {
if (user.displayName === userObj.data().displayName) {
return user.lastName;
}
});
docs.value = doc;
}
};
onMounted(returnUser)
return { user, docs, returnUser };
},
};