Problems with Snapshot for Firebase, need workaround

I am working on react project and am new to using firebase. Basically I am doing a query to get user's data and I want to reference it in the html but it does not let me because I am using a snapshot. I can't set data from the snapshot of the query to a global variable because I don't think it exists out of the snapshot. Is there a way to get the query's data outside of snapshot?

    let usersname = "";
    const myFunction = async () => {
        let user = window.sessionStorage.getItem("user");
        const q = query(accountsCollectionRef, where("username", "==", user));

        onSnapshot(q, (snapshot) => {
            let queryData = [];
            snapshot.docs.forEach((doc) => {
                queryData.push({ ...doc.data(), id: doc.id })
            })
           usersname = queryData[0].name;
           
        })
    }
    myFunction();
    console.log(usersname);

Upvotes: 0

Views: 58

Answers (1)

Mises
Mises

Reputation: 4613

You need to check are response exits, this is how you do it.

onSnapshot(q, snapshot => {
            if(!snapshot.empty) {
                usersname = snapshot.docs[0].data().name
            } else {
                usersname = ""
            }
        })

I just shortened the thing you did in your function. Check are it work, most important is if(snapshot.exists()) this is way you check are response have data. Remember to unsubscribe snapshot.

Upvotes: 1

Related Questions