在 React-Native 中显示来自 Firestore 的用户名数据

时间:2021-04-25 11:35:52

标签: javascript firebase react-native google-cloud-firestore

我是 React-Native 的新手。我想在屏幕上显示每个用户的名字。现在,我可以显示带有“currentUser.email”的电子邮件,但无法从 firestore 获取用户的姓名。 这是代码:

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);
      });
  };

1 个答案:

答案 0 :(得分:0)

如果您的 getUser 函数有效,您可以使用以下命令从同一集合中获取所有用户数据:

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

另请参阅 getting all documents from a collection 上的 Firebase 文档。