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
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
}
}
Assuming you have a Firestore collection called ‘users’ to store user information:
Now, you can display the email ID next to each message in your Chat component: