-1
import { React, useEffect, useState } from "react";
import { Link, useNavigate } from "react-router-dom";
import "../index.css";
import "bootstrap/dist/css/bootstrap.css";
import Navbar1 from "./NavBar1";
import { db } from "../firebase";
import { auth } from "../firebase";
import { useAuthValue } from "../context.js";
import { onAuthStateChanged } from "firebase/auth";
import {
  collection,
  getDocs,
  doc,
  updateDoc,
  arrayUnion,
  getDoc,
} from "firebase/firestore";

const JoinedRooms = () => {
  const { currentUser } = useAuthValue();
  const [listOfRooms, setListOfRooms] = useState([]);

  // console.log(currentUser);
  const uid = currentUser.uid;

  const getListOfRooms = async () => {
    const docRef = doc(db, "Users", uid);
    const docSnap = await getDoc(docRef);

    if (docSnap.exists()) {
      console.log("Document data:", docSnap.data());
      setListOfRooms(docSnap.data().Chatrooms);
      console.log(listOfRooms);
    } else {
      // doc.data() will be undefined in this case
      console.log("No such document!");
    }
  };

  const getRoomInfo = async ({ id }) => {
    const docRef = doc(db, "Rooms", id);
    const docSnap = await getDoc(docRef);

    if (docSnap.exists()) {
      console.log("Document data:", docSnap.data());
    } else {
      // doc.data() will be undefined in this case
      console.log("No such document!");
    }
  };

  const getRoomInfoHelper = () => {
    listOfRooms.map((s) => {
      const { id } = s;
      getRoomInfo(id);
    });
  };

export default JoinedRooms;

I tried using useState but it runs into infinite loop. I also tried putting the value into a var variable but then i am not able to access the value inside the jsx. I am not able to figure out how and when to call this function and when to assign the value to the variable.

anothermh
  • 9,815
  • 3
  • 33
  • 52
Rahul
  • 1
  • 1
  • Please include a [minimal reproducible example](https://stackoverflow.com/help/minimal-reproducible-example) in your post. It should include your exact inputs, exact outputs, and detailed steps you took so that the problem can be reproduced by others. This is not a *minimal* example -- we don't need to know that you're using things like bootstrap. – anothermh Apr 01 '23 at 18:12

1 Answers1

1

Setting state is an asynchronous operation, so by the time you console.log(listOfRooms); its value hasn't been set yet. For more on this see:

To prevent the constant reloading, you'll want to put the loading of the data in a useEffect hook - so that it only runs when necessary, rather then whenever the component renders. For more on this, see:

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807