0

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)
        }
    })
1
  • If an answer was useful, click the upvote button (▲) to the left of it (although you may not have enough reputation to do this yet). If it answered your question, click the checkmark (✓) to accept it (which you can do, since you asked the question). That way others know that you've been (sufficiently) helped. Also see What should I do when someone answers my question? Commented May 12, 2020 at 15:32

1 Answer 1

1

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]);
};

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.