Here I'm taking all the docs from Firestore:
useEffect(() => {
const getUsers = async () => {
const data = await getDocs(usersCollectionRef);
setUsers(data.docs.map((doc) => ({
...doc.data(),
id: doc.id,
})))
};
getUsers();
}, []);
Then I put it on the following div to show the details:
<div>
{users.map((user) => {
return (<div className="card-body" key={user.id}>
<p className="card-text"><u>User details</u></p>
<p className='card-text'>User : {user.id}</p>
<p className='card-text'>User : {user.name}</p>
<p className='card-text'>Your weight : {user.weight}</p>
<p className='card-text'>Your height : {user.height}</p>
<p className='card-text'>Age : {user.age}</p>
</div>)
})}
</div>
It shows all the documents of all the users if there is more than 1 user in the Firestore DB: On the below image you can see the details of both user that is stored in the DB
CodePudding user response:
You are fetching all documents from the collection using getDocs(collectionRef)
. If you want to fetch current user's document only then you can use getDoc()
with a DocumentReference
instead as shown below:
const [user, setUser] = useState(null);
useEffect(() => {
onAuthStateChanged(auth, (user) => {
if (user) {
const uid = user.uid;
const snapshot = await getDoc(doc(db, "users", uid));
if (snapshot.exists()) {
setUser(snapshot.data())
} else {
console.log("User doc missing")
}
} else {
console.log("User not logged in")
setUser(null);
}
});
}, []);
Then you don't have to use map
as user
is not an array:
<div>
{true ? (
<div className="card-body" key={user.id}>
<p className="card-text">
<u>User details</u>
</p>
<p className="card-text">User : {user.id}</p>
<p className="card-text">User : {user.name}</p>
<p className="card-text">Your weight : {user.weight}</p>
<p className="card-text">Your height : {user.height}</p>
<p className="card-text">Age : {user.age}</p>
</div>
) : (
<p>No user logged in</p>
)}
</div>