vasilis 123
vasilis 123

Reputation: 665

cannot fetch data from firestore to react app

This is my first time using firestore and I have a user profile page . I have inserted some users in a firestore db and I try to access user by email to console.log his data for testing purposes . However when I try to fetch data from cloud firestore I get that I have no documents in my db while I have

My code :

firebase.js

import firebase from 'firebase/app';
import "firebase/auth";
import "firebase/firestore";
const app = firebase;
export const auth = app.auth();
export default app;

export const db = firebase.firestore();
export const userCollection = db.collection('users');


export const CreateUser = async (email,password,username)=>{
  const authResult = await auth.createUserWithEmailAndPassword(email,password);
  userCollection.doc(authResult.user.uid)
    .set({
      created:firebase.firestore.FieldValue.serverTimestamp(),
      Email:email,
      userName:username
    });
}

export const GetUserName = (email)=>{  //no doc exists  
  try{
    userCollection.doc(email) 
      .get()
      .then(doc=>{
        const docData = doc.data();
        console.log({docData});
      })
  }catch(error){
      alert(error.message);
  }
}

ProfilePage.js

import {React , useEffect} from 'react';
import {useAuth} from './UserContext';
import Button from '@material-ui/core/Button';
import {useHistory} from 'react-router-dom';
import 'firebase/firestore';
 import {GetUserName} from '../firebase';
 
//need to display username in profilepage {user.username}

export default function ProfilePage(){
  
  const history = useHistory();
  const {user , logout} = useAuth();
  

  
  const handleLogout = async ()=>{
    try{
       await logout();
       history.push('/login');
    }catch(err){
      alert(err.message);
    }
  }

  useEffect(()=>{  //call the function from firebase.js that console.logs data 
    GetUserName(user.email);
  },[]) 

  return ( //this displays a user like "hi [email protected]" and works 
    <div>
      <h1>Hi {user.email} </h1> 
      <Button onClick={handleLogout} color = "primary" variant = "outlined">Log out</Button>
    </div>
  );
}

So the problem is react does not recognize I have docs inside my firestore collection

UPDATE : by removing if(!doc.exists) from firebase.js I get docData is undefined

Upvotes: 0

Views: 276

Answers (1)

Renaud Tarnec
Renaud Tarnec

Reputation: 83048

If I am not mistaking, you create a user document with an ID corresponding to the user’s ID but in the GetUserName() method you try to get a user document with an ID corresponding to an email.

If you really want to query the users collection by email you should use a query.

Upvotes: 1

Related Questions