Skip to content
Advertisement

How to get info from firebase firestore database in react-native

I am trying to get the logged-in user info from my firestore database in my react native app.

I am new to react native, therefore I don’t know the correct syntax or methodology to do these things with firestore.

I’ve read many documentations but they don’t provide information for every situation and instance.

here is my code:

my AuthProvider.js:

export const AuthContext = createContext();
export const AuthProvider = ({children}) => {
const [user,setUser] = useState(null);

my profileScreen.js:

const {user} = useContext(AuthContext);

  const snapshot =  firestore().collection('Users').doc(user.uid).get();

  const name = snapshot("name");
  const email = snapshot("email"); //this code gives me and error, 
  snapshot is not a function, snapshot is an instance of a promise

How can I fetch a single user’s information, or in general how can I fetch information from firestore with react-native?

UPDATE:

i tried this following code, but in the console i get undefined for the name. why is that?

        firestore()
        .collection("Users")
        .doc(user.uid)
        .get()
        .then((snapshot) => {
          const name = snapshot.name
          console.log(name)
        });

Advertisement

Answer

You could try the following:

     firebase.firestore()
            .collection("COLLECTION_NAME")
            .doc("DOC_NAME")
            .get()
            .then((snapshot) => {
                ...
                })
                

Depending on what you get and what are you using. For example, if you want to fetch the data you will have a collection of all users, in which each document will be a different user/id. And to get the data of the current authenticated user, you can use firebase.auth().currentUser.uid(replace it with the “DOC_NAME” in the code above).

For example, to display a greeting message to a specific logged in user, you will have to use useState from rn.

   const [userInfo, setUserInfo] = useState([]);

then write that function

   firebase.firestore()
   .collection("allUsers") -> replace with collection where u keep all users 
   .doc(firebase.auth().currentUser.uid)(that gets the uid of current authenticated user)
   .get() 
   .then((snapshot) => { 
     if (snapshot.exists) 
       { setUserInfo(snapshot.data()); 
       } else {  } 
     })

And then, in your component, you can display user name, email, age etc, depending on your field.

For example, if your user has a field “name” with name on it, you can display it like this:

        <Text>{userInfo.name}</Text>
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement