Reputation: 23
I'm currently trying to get data from a firestore database. I can get a promise with an array, but I want to get just the array. My code looks like this:
function getUserData(){
return database.users.where("uid", "==", currentUser.uid).get().then((q) => {
return q.docs.map(doc => doc.data())
})
}
var data = getUserData()
console.log(data)
Upvotes: 0
Views: 810
Reputation: 9118
You're trying to get a result from a function that returns the promise, not the array itself, so you need to wait for the promise to finish executing and return the result. You can do it in two ways:
then
:getUserData().then((data) => console.log(data));
async
/await
:async function test() {
const data = await getUserData();
console.log(data);
}
Upvotes: 1
Reputation: 595
You can get data using state.
Like this.
const [data, setData] = useState([]);
function getUserData(){
database.users.where("uid", "==", currentUser.uid).get().then((q) => {
const d = q.docs.map(doc => doc.data())
setData(d);
})
}
getUserData()
useEffect(() => {
console.log(data)
}, [data])
Upvotes: -1
Reputation:
You're missing async/await.
function getUserData() {
return await database...
You also need to await the function call.
var data = await getUserData()
Read up on asyncronous code and using async/await. You're getting "promise" returned because when you're trying to console the output, the code hasn't finished processing yet, so it's in a "pending promise state" instead of resolved or rejected. Edit: The .then is correct, but it's only telling it what to do in the function call. So you have to await the function call as well.
Upvotes: 2