Fetching data from Firestore in React

I am creating a chat application in React using Firebase. I am focusing on Group chats mostly. I am not able to fetch the messages from Firestore. I am able to Post the messages to db but not retrieve it. Here’s the Chat.js component code.

onst Chat = ({ groupId }) => {
  const [messages, setMessages] = useState([]);
  const scroll = useRef();
  const [selectedGroupId, setSelectedGroupId] = useState(null);

  const chatGroupsData = [
    { id: 'Group1', name: 'Group1' },
    { id: 'Group2', name: 'Group2' },
  ];

  const handleGroupSelection = (selectedGroupId) => {
    setSelectedGroupId(selectedGroupId);
  };

  useEffect(() => {
  if (groupId) { 
    console.log("Fetching messages for groupId:", groupId);
    const messagesCollectionRef = collection(db, 'ChatGroups', groupId, 'Messages');
    const q = query(messagesCollectionRef, orderBy('timestamp'));
    const unsubscribe = onSnapshot(q, (querySnapshot) => {
      let messages = [];
      querySnapshot.forEach((doc) => {
        messages.push({ ...doc.data(), id: doc.id, groupId });
      });
      setMessages(messages);
    }, (error) => {
      console.error('Error fetching messages:', error);
    });
    
    return () => unsubscribe();
  }
}, [groupId]);

console.log("Messages:", messages);

  return (
    <div className="flex h-screen">
      {/* Chat List (Left Side) */}
      <div className={style.chatList}>
        {/* Chat list content */}
        <Sidebar chatGroups={chatGroupsData} onSelectGroup={handleGroupSelection} />
      </div>
      
      {/* Chat Interface (Right Side) */}
      <div className={style.chatInterface}>
        <div className={style.chatHeader}>
        <h2 className="text-xl font-semibold">Mental Health</h2> {/* Adjust the title */}
        </div>
        {/* Chat Messages */}
        <main className={style.main}>
          {examplemessages &&
            examplemessages
            .filter((message) => message.groupId === selectedGroupId) // Filter messages by groupId
            .map((message) => (
            <Message key={message.id} message={message} groupId={selectedGroupId} />
          ))}
        </main>
        {/* Send Message Component */}
        <SendMessage scroll={scroll} groupId={selectedGroupId} />
      </div>

      {/* Scroll Indicator */}
      <span ref={scroll}></span>
      
    </div>
    
  );
};

All the necessary imports are made. I’ve cross checked with all other components are working fine.

I’ve tried hardcoding the sample messages in the component itself which are successfully rendered. Also the console.log("Messages:", messages); returns and empty array.