Home > Enterprise >  Unable to retrieve document ID from Firebase query in useEffect function
Unable to retrieve document ID from Firebase query in useEffect function

Time:02-04

I have the following function set up and it's sending data to "userInfo" correctly, but how do I access the value of "id" to use in another function?

const [userInfo, setUserInfo] = useState("");

    const userID = auth.currentUser.uid;

    //function for automatically retrieving user
    useEffect(() => {
        const q = query(collection(db, 'users'), where("uid", "==", userID));
        onSnapshot(q, (querySnapshot) => {
            setUserInfo(querySnapshot.docs.map(doc => ({
                id: doc.id,
                data: doc.data()
            })))
        })
        console.log(userInfo);
    }, [])

Keep in mind "uid" is different than "id". "id" is the document ID and "uid" is a value stored within the document.

When I run console.log(userInfo) it gives me an array of objects. The only thing I need to access is the value of "id".

I tried doing console.log(userInfo[0].id) and this works until I reload the page and then I get this error:

Uncaught TypeError: Cannot read properties of undefined (reading 'id')

CodePudding user response:

You initialize your useState to an empty string "", and you change it inside a useEffect. Since useEffect fires once the page has rendered, you will at somepoint console.log(userInfo[0].id) while your useState is still a string

What happens when you try to access userInfo[0].id if userInfo is a string? You are trying to access something undefined

if you console.log the following with will not crash:

console.log(userInfo[0]?.id) //the **?** checks if the obj has the following prop
  • Related