skip to Main Content

I am new to Firebase and want to get the email id of each user and display it next to the message. I came across the code I have attached below and am able to get the photourl of each user and display it next to each users message and want tot get the email Id now

function Chat() {
  const scroll = useRef()
  const [messages, setMessages] = useState([])
  // var email = firebase.auth().currentUser && firebase.auth().currentUser.email;
  useEffect(() => {
      db.collection('messages').orderBy('createdAt').limit(50).onSnapshot(snapshot => {
          setMessages(snapshot.docs.map(doc => doc.data()))
            
     })
  }, [])
  return (
      <div>
          <SignOut />
          <div className="msgs">
              {messages.map(({ id, text, photoURL, uid , emailid}) => (
                  <div>
                      <div key={id} className={`msg ${uid === auth.currentUser.uid ? 'sent' : 'received'}`}>
                          <img style={{  width: "40px", height: "40px",margin: "2px 5px",borderRadius:"50%"}} 
                          src={photoURL} alt="" />
                          {emailid}
                          <p>{text}</p>
                      </div>
                  </div>
              ))}
          </div>
          <SendMessage scroll={scroll} />
          <div ref={scroll}></div>
      </div>
function SendMessage({ scroll }) {
  const [msg, setMsg] = useState('')

  async function sendMessage(e) {
      e.preventDefault()
      const { uid, photoURL, emailid } = auth.currentUser

      await db.collection('messages').add({
          text: msg,
          photoURL,
          uid,
         
          createdAt: firebase.firestore.FieldValue.serverTimestamp()
      })
      setMsg('')
      scroll.current.scrollIntoView({ behavior: 'smooth' })
  }
  return (
      <div>
                  {/* <input style={{ maxWidth: "1000px", fontSize: '15px', fontWeight: '550', marginLeft: '25px', marginBottom: '-3px' }} placeholder='Message...' type="text" value={msg} onChange={e => setMsg(e.target.value)} /> */}
                
      
          <form onSubmit={sendMessage}>
              {/* <div className="sendMsg"> */}
                 <div className="input1">
                 </div>
                  <input style={{maxWidth: "1000px",color:"white", background: "rgb(59, 59, 59)", width: "800px", fontSize: '15px', fontWeight: '550', marginLeft: '25px', marginBottom: '-3px' }} placeholder='Message...' type="text" value={msg} onChange={e => setMsg(e.target.value)} />
                  

                  <button style={{ width: '20%', fontSize: '15px', fontWeight: '550', margin: '4px 5% -13px 5%', maxWidth: '200px', color:"white"}} type="submit">Send</button>

              {/* </div> */}
          </form>
      </div>
  )

2

Answers


  1. Chosen as BEST ANSWER

    auth().currentUser.email will give the current email then I get that in the SendMessage component and then display it in the Chat component, go through the components it will be clear

    function Chat() {
    const scroll = useRef()
    const [messages, setMessages] = useState([])
    // var email = firebase.auth().currentUser && firebase.auth().currentUser.email;
    useEffect(() => {
        db.collection('messages').orderBy('createdAt').limit(50).onSnapshot(snapshot => {
            setMessages(snapshot.docs.map(doc => doc.data()))
       
       })
    }, [])
    return (
        <div>
            <SignOut />
            <div className="msgs">
                {messages.map(({ id, text, photoURL, uid , email}) => (
                    <div>
                        <div key={id} className={`msg ${uid === auth.currentUser.uid ? 'sent' : 'received'}`}>
                        <p>{email}</p> <br></br>
                            <img style={{  width: "40px", height: "40px",margin: "2px 5px",borderRadius:"50%"}} 
                            src={photoURL} alt="" /><br></br>
                          
                            <p>{text}</p><br></br>
                        </div>
                    </div>
                ))}
            </div>
            <SendMessage scroll={scroll} />
            <div ref={scroll}></div>
        </div>
    )
    

    }

    function SendMessage({ scroll }) {
    const [msg, setMsg] = useState('')
    
    async function sendMessage(e) {
        e.preventDefault()
        const { uid, photoURL, email } = auth.currentUser
    
        await db.collection('messages').add({
            text: msg,
            photoURL,
            uid,
            email,
            createdAt: firebase.firestore.FieldValue.serverTimestamp()
        })
        setMsg('')
        scroll.current.scrollIntoView({ behavior: 'smooth' })
    }
    return (
        <div>
                    {/* <input style={{ maxWidth: "1000px", fontSize: '15px', fontWeight: '550', marginLeft: '25px', marginBottom: '-3px' }} placeholder='Message...' type="text" value={msg} onChange={e => setMsg(e.target.value)} /> */}
                  
        
            <form onSubmit={sendMessage}>
                {/* <div className="sendMsg"> */}
                   <div className="input1">
                   </div>
                    <input style={{maxWidth: "1000px",color:"white", background: "rgb(59, 59, 59)", width: "800px", fontSize: '15px', fontWeight: '550', marginLeft: '25px', marginBottom: '-3px' }} placeholder='Message...' type="text" value={msg} onChange={e => setMsg(e.target.value)} />
                    
    
                    <button style={{ width: '20%', fontSize: '15px', fontWeight: '550', margin: '4px 5% -13px 5%', maxWidth: '200px', color:"white"}} type="submit">Send</button>
    
                {/* </div> */}
            </form>
        </div>
    )
    

    }


  2. Assuming you have a Firestore collection called ‘users’ to store user information:

    // In your Chat component
    const [messages, setMessages] = useState([]);
    
    useEffect(() => {
      // Fetch user data from Firestore for each message sender
      db.collection('messages')
        .orderBy('createdAt')
        .limit(50)
        .onSnapshot(async (snapshot) => {
          const messageData = [];
          for (const doc of snapshot.docs) {
            const message = doc.data();
            // Fetch the user's email using the UID from 'users' collection
            const userDoc = await db.collection('users').doc(message.uid).get();
            const userData = userDoc.data();
            message.emailid = userData.email; // Add email to the message
            messageData.push(message);
          }
          setMessages(messageData);
        });
    }, []);
    

    Now, you can display the email ID next to each message in your Chat component:

    {messages.map(({ id, text, photoURL, emailid }) => (
      <div key={id} className={`msg ${uid === auth.currentUser.uid ? 'sent' : 'received'}`}>
        <img style={{ width: "40px", height: "40px", margin: "2px 5px", borderRadius: "50%" }}
          src={photoURL} alt="" />
        {emailid} {/* Display email ID */}
        <p>{text}</p>
      </div>
    ))}
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search