简体   繁体   中英

How to get values of a field in Firestore in React

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' .

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

let alertField = docSnap.data().alert_state

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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM