'Fetching document references in a document in Firebase / Reactjs

I'm trying to learn ReactJS and Firebase

I have a user collection in firebase with user documents. Each user has the following fields: (name, uid, authProvider, email.... myGroups)

screenshot of user collection:

screenshot of user collection

myGroups is an array with document references to documents in a collection called 'groups'. I am interested in getting the document references in the myGroups array.

  // My groups
  const [user, loading, error] = useAuthState(auth); // get user token from website
  const [myGroups, setMyGroups] = useState([]);
  useEffect(() => {
    if (loading) {
      // maybe trigger a loading screen if we need
      return;
    }
  }, [user, loading]);

  useEffect(() => {
    getMyGroups();
    console.log(myGroups);
  }, []);

  const getMyGroups = async () => {
    if (user) {
      console.log("Fetching user");
      fetchUser(user).then((data) => {
        const mg = [];
        data.myGroups?.forEach((d) => {
          getDoc(d).then((docSnapshot) => {
            const groupData = docSnapshot.data();
            let name = groupData.name;
            let interests = groupData.interests;
            let members = groupData.members;
            let description = groupData.description;
            let event = groupData.event;
            let matches = groupData.matches;
            let g = new Group(
              name,
              interests,
              members,
              description,
              event,
              matches
            );
            mg.push(g);
          });
        });
        setMyGroups(mg);
        console.log(myGroups);
      });
    }
  };

The fetchUser function looks like this:

export const fetchUser = async (user) => {
  try {
    const q = query(collection(db, "users"), where("uid", "==", user.uid));
    const doc = await getDocs(q);
    const data = doc.docs[0].data();
    return data;
  } catch (err) {
    console.error(err);
    alert("An error occured while fetching user data");
  }
};

However, I keep getting undefined when mapping the myGroups array to an object.

        <div className="avatars">
          {console.log(myGroups)}
          {myGroups.map((object, i) => (
            <GroupAvatar
              name={object.name}
              key={i}
              link="https://api.lorem.space/image/pizza?w=220&h=220"
            />
          ))}
          <AddGroup />
        </div>

My browser sometimes console logs the user array, other times myGroups is an empty array.

Am I misunderstanding how useEffect works?

The snippet below works when fetching documents from a collection:

 //All groups
  const [groups, setGroups] = useState([]);
  const groupsCollectionRef = collection(db, "groups");
  useEffect(() => {
    const getGroups = async () => {
      const data = await getDocs(groupsCollectionRef);
      setGroups(data.docs.map((doc) => ({ ...doc.data(), id: doc.id })));
    };
    getGroups();
  }, []);


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source