简体   繁体   中英

Display username data from Firestore in React-Native

I'm new in React-Native. I want to display the name from each user in a screen. For now, i can display the email with "currentUser.email" but it didn't work to get the name of the user from firestore. This is the code:

export default function AddScreen({navigation, route}) {
  const [image, setImage] = useState(null);
  const [uploading, setUploading] = useState(false);
  const [title, setTitle] = useState(null);
  const [author, setAuthor] = useState(null);
  const [genre, setGenre] = useState(null);
  const [summary, setSummary] = useState(null);
  const [price, setPrice] = useState(null);
  const [userData, setUserData] = useState(null);

  const user = firebase.auth().currentUser;
  const userId = firebase.auth().currentUser.uid;

..........................................................................

  const getUser = async () => {
    await firestore()
      .collection('user')
      .doc(user.uid)
      .get()
      .then(documentSnapshot => {
        if (documentSnapshot.exists) {
          console.log('User Data', documentSnapshot.data());
          setUserData(documentSnapshot.data());
        }
      });
  };
  const userName = firebase.auth().currentUser.email;
  const submitBookPost = async () => {
    const imageUrl = await postBookImage();
    console.log('Image Url:', imageUrl);

    firestore()
      .collection('user_book')
      .add({
        userId: userId,
        title: title,
        userName: userName,
        bookImg: imageUrl,
        postTime: firestore.Timestamp.fromDate(new Date()),
        author: author,
        genre: genre,
        summary: summary,
        price: price,
      })
      .then(() => {
        console.warn('Book Added!');
        Alert.alert(
          'Book published!',
          'Your book has been successfully added to Market!',
        );
        setTitle(null);
        setAuthor(null);
        setGenre(null);
        setSummary(null);
        setPrice(0);
      })
      .catch(error => {
        console.warn('Something went wrong.', error);
      });
  };

If your getUser function works, you could get all user data from the same collection with:

db.collection("user").get().then((querySnapshot) => {
    querySnapshot.forEach((doc) => {
        console.log(doc.id, " => ", doc.data());
    });
});

Also see the Firebase documentation on getting all documents from a collection .

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