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>
);
}
ahmad raza is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.