React Naive Create Group Chat Firebase Realtime Database

I create a chat app in React Native and Firebase Realtime Database first of all user can chat private that is working fine as well as user can create group chat inside the React Native appp that is also working fine but I want to create group chat from React JS web admin dasborad not a logged in user create group only on create group from web admin and add user to group when I create group from admin the group chat successfuly created in firebase realtime but not retrive in React Ntive app if I create group chat from React Native app the created group is apear on inbox here is my code both web admin and react native app:

ignore my English many thanks

I am expecting to create group from admin dashbord

const CreateGroup = () => {
    const [groupName, setGroupName] = useState('');
    const [users, setUsers] = useState([]);
    const [selectedUsers, setSelectedUsers] = useState([]);
    const [error, setError] = useState('');
    const [isLoading, setIsLoading] = useState(false);

    useEffect(() => {
        const fetchUsers = async () => {
            try {
                const usersCollection = collection(firestore, 'users');
                const snapshot = await getDocs(usersCollection);
                const usersList = snapshot.docs.map(doc => ({ id: doc.id, ...doc.data() }));
                setUsers(usersList);
            } catch (error) {
                setError('Failed to fetch users');
                console.error(error);
            }
        };
        fetchUsers();
    }, []);

    const handleCreateGroup = async () => {
        setIsLoading(true);
        setError('');
        try {
            const dbRef = ref(database, 'chats');
            const newGroupRef = push(dbRef);
            const newGroupData = {
                chatName: groupName,
                createdAt: new Date().toISOString(),
                createdBy: selectedUsers,
                updatedBy: selectedUsers,
                isGroupChat: true,
                latestMessageText: 'Welcome to the group!',
                updatedAt: new Date().toISOString(),
                users: selectedUsers,
                chatImage: "",  
            };

            await update(newGroupRef, newGroupData);
            console.log(`Group created with data: ${JSON.stringify(newGroupData)}`);

            const messagesRef = ref(database, `messages/${newGroupRef.key}`);
            await push(messagesRef, {
                senderId: 'system',
                text: 'Welcome to the group!',
                timestamp: new Date().toISOString(),
            });

            const updates = {};
            selectedUsers.forEach(userId => {
                updates[`userChats/${userId}/${newGroupRef.key}`] = true;
            });

            await update(ref(database), updates);
            console.log('Updates applied to userChats:', updates);

            console.log('Group created with ID:', newGroupRef.key);
            alert('Group created successfully!');
            setIsLoading(false);
        } catch (error) {
            setError('Error creating group');
            console.error(error);
            setIsLoading(false);
        }
    };

    return (
        <div>
            <h1>Create Group</h1>
            <input 
                type="text" 
                value={groupName} 
                onChange={(e) => setGroupName(e.target.value)} 
                placeholder="Group Name" 
            />
            <div>
                <h2>Select Users</h2>
                {users.map(user => (
                    <div key={user.id}>
                        <input
                            type="checkbox"
                            value={user.id}
                            checked={selectedUsers.includes(user.id)}
                            onChange={(e) => {
                                const id = user.id;
                                setSelectedUsers(prev => 
                                    e.target.checked ? [...prev, id] : prev.filter(uid => uid !== id)
                                );
                            }}
                        />
                        {user.userName}
                    </div>
                ))}
            </div>
            {error && <p style={{ color: 'red' }}>{error}</p>}
            <button onClick={handleCreateGroup} disabled={isLoading}>
                {isLoading ? 'Creating...' : 'Create Group'}
            </button>
        </div>
    );
};

useEffect(() => {
  console.log("Subscribing to firebase listeners");

  const app = getFirebaseApp();
  const dbRef = ref(getDatabase(app));
  const userChatsRef = child(dbRef, `userChats/${userData.userId}`);
  const refs = [userChatsRef];
  const db = getFirestore(app);  

  onValue(userChatsRef, (querySnapshot) => {
    const chatIdsData = querySnapshot.val() || {};
    const chatIds = Object.values(chatIdsData);

    const chatsData = {};
    let chatsFoundCount = 0;

    chatIds.forEach(chatId => {
      const chatRef = child(dbRef, `chats/${chatId}`);
      refs.push(chatRef);

      onValue(chatRef, (chatSnapshot) => {
        chatsFoundCount++;
        const data = chatSnapshot.val();

        if (data) {
          data.key = chatSnapshot.key;

          const userPromises = data.users.map(userId => {
            if (storedUsers[userId]) return Promise.resolve();

            const userRef = doc(db, "users", userId);
            return getDoc(userRef)
              .then(userSnapshot => {
                if (userSnapshot.exists()) {
                  const userSnapshotData = userSnapshot.data();
                  dispatch(setStoredUsers({ newUsers: { [userId]: userSnapshotData } }));
                }
              })
              .catch(error => {
                console.error(`Error fetching user data: ${error}`);
              });
          });

          Promise.all(userPromises).then(() => {
            chatsData[chatSnapshot.key] = data;

            if (chatsFoundCount >= chatIds.length) {
              dispatch(setChatsData({ chatsData }));
              setIsLoading(false);
            }
          });
        }

        if (chatsFoundCount === 0) {
          setIsLoading(false);
        }
      });

      const messagesRef = child(dbRef, `messages/${chatId}`);
      refs.push(messagesRef);

      onValue(messagesRef, messagesSnapshot => {
        const messagesData = messagesSnapshot.val();
        dispatch(setChatMessages({ chatId, messagesData }));
      });
    });
  });

  return () => {
    console.log("Unsubscribing firebase listeners");
    refs.forEach(ref => off(ref));
  };
}, [dispatch, userData.userId, storedUsers]);

if (isLoading) {
  return (
    <View style={{justifyContent:'center', alignItems:'center'}}>
      <ActivityIndicator size={'large'} color={Color.colorDarkslateblue} />
    </View>
  );
}

New contributor

ahmad raza is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật