Home > Mobile >  How can I pull all values from a Firestore document in React Native?
How can I pull all values from a Firestore document in React Native?

Time:07-05

This is my database and the data I want to pull:

This is my code:

const MatchScreen = ({route}) => {

  const id = route.params.id;
  const booking = getDoc(doc(db, 'bookings', id))
  console.log(booking)

  return (
    <View style = {{justifyContent: 'center', alignItems: 'center'}}>
      <Text>{id}</Text>
  </View>
  )
      }

I got the id value from another page and that one is displayed properly on the screen, but when I try to console log booking to see if the values are there, this is what I get:

Promise {
  "_U": 0,
  "_V": 0,
  "_W": null,
  "_X": null,
}

What am I doing wrong?

CodePudding user response:

When you call getDoc you get back a Future<DocumentSnapshot>. So to get the value from that, you have to use then() or await to resolve the Future and then call data() to get the document data.

const booking = getDoc(doc(db, 'bookings', id))
booking.then((doc) => {
  console.log(doc.data());
});

This is quite well covered in the documentation on getting a document, so I recommend spending some time there.

CodePudding user response:

Getting a document from Firestore's Collection is an asynchronous operation and it is required to run the side effects code inside useEffecthook.

const MatchScreen = ({ route }) => {
  const [booking, setBooking] = useState(null);
  const bookingId = route.params.id;

  function getBooking(bookingId) {
    getDoc(doc(db, "bookings", bookingId)).then((snapshot) => {
      if (snapshots.exists) {
        booking = snapshots.data();

        setBooking(booking);
      }
    });
  }

  useEffect(() => {
    getBooking();
  }, []);

  console.log(" Booking :", booking);

  return (
    <View style={{ justifyContent: "center", alignItems: "center" }}>
      <Text>{bookingId}</Text>
    </View>
  );
};```


  • Related