Home > Software engineering >  How to get values of a field in Firestore in React
How to get values of a field in Firestore in React

Time:04-07

I use a document in firestore that stores three fields with boolean values. This boolean values I need for further processsing. In my programm I want to read this values. But how to read the fields of a document? As explained here it should work like following:

const getStateEntries = async () => {
  await getDoc(doc(db, 'Collection_Name', 'Document_ID'))
  .then((docSnap)=> {
    let alertField = docSnap.data['alert_state']
    console.log(alertField)
  })
  setAlertState(alertField)
}

When I run the code it looks like get no access to the field. When I print the variable to the console, I get an 'undefined'.

CodePudding user response:

The data is not a property on DocumentSnapshot. Try refactoring the code as shown below:

let alertField = docSnap.data().alert_state

CodePudding user response:

You can get something like below code:

firestore()
  .collection('Users')
  .get()
  .then(querySnapshot => {
    console.log('Total users: ', querySnapshot.size);

    querySnapshot.forEach(documentSnapshot => {
      console.log('User ID: ', documentSnapshot.id, documentSnapshot.data());
    });
  });

For reference use, this one: https://rnfirebase.io/firestore/usage

Hope it will help you!

  • Related