Buddy Bob
Buddy Bob

Reputation: 5889

Return value from Firestore instead of console.logging it. - React

I've looked at the firestore doc. on how to retrieve data and it works fine. But I am not able to store the value in a variable. I've taken a look here How to return value from firestore database? but the answer end result is still a console.log(result);.

function returnUserData(userId){
  let docRef = db.collection("users").doc(userId)
  return docRef.get().then((doc) => {
    if (doc.exists) {
        doc.data()
        return doc.data();
    } else {
        // doc.data() will be undefined in this case
        console.log("No such document!");
    }
  }).catch((error) => {
      console.log("Error getting document:", error);
  });
}
returnUserData(localStorage.getItem("currentUserId")).then(result => {
  console.log(result);
})

How would I be able to return an actual value of returnUserData?

Upvotes: 0

Views: 43

Answers (1)

Phil
Phil

Reputation: 164924

In a typical React app where you want to set a state value from the result, you would make async calls like this within a useEffect hook and set the state value after it resolves

const [doc, setDoc] = useState()

useEffect(() => {
  returnUserData(localStorage.getItem("currentUserId")).then(result => {
    setDoc(result)
  })
}, [])

Upvotes: 2

Related Questions