Reputation: 173
I'm trying to see if any users are already enrolled in a class. I'm trying to set the state classesArray into an array of the classes that they are already enrolled in. For some reason, it performs the action inside if(user) even though user is undefined.
const Button = ({currentPage, currentCourse, user}) =>
{
const [classesArray, setArray] = useState([]);
useEffect(()=>{
if (user)
{
let tempArray = db.collection('users').doc(user.id).classes;
console.log(tempArray)
}
})
Upvotes: 0
Views: 53
Reputation: 13702
if
won't get executed for undefined
or null
or false
values. Your user
prop may be an empty object (which is considered as ok in the if
check). So be specific with your if condition eg: if(user.id)
Note: you need to make corrections in your useEffect code. Also your useEffect runs on each and every re-render, so add a dependency to it(user for ex.)
const Button = ({ currentPage, currentCourse, user }) => {
const [classesArray, setArray] = useState([]);
useEffect(() => {
if (user.id) {
let docRef = db.collection("users").doc(user.id);
docRef
.get()
.then(function(doc) {
if (doc.exists) {
console.log("Document data:", doc.data());
} else {
// doc.data() will be undefined in this case
console.log("No such document!");
}
})
.catch(function(error) {
console.log("Error getting document:", error);
});
}
}, [user.id]);
};
Upvotes: 1