I am trying to add a list of online users to my chat app, but I ran into this problem:
On the front end I emit the currently logged in user's name, and then update the state of my users array:
useEffect(() => {
if (Auth.loggedIn()) {
const { data } = Auth.getUserInfo();
socket.emit("user_connected", data.username);
}
// if I remove these brackets I get an infinite loop in my server
}, []);
useEffect(() => {
socket.on("online_users", (onlineUsers) => {
setUsers(onlineUsers);
console.log(users);
});
});
I created the user array in the back end using the emitted username:
const onlineUsers = [];
io.on("connection", (socket) => {
socket.join("public_chat");
console.log(`A user has joined the chat`);
socket.on("user_connected", (user) => {
const userExists = checkUserArray(user, onlineUsers);
if (!userExists) {
onlineUsers.push({ user, id: socket.id });
}
console.log(onlineUsers);
socket.in("public_chat").emit("online_users", onlineUsers);
console.log(`${user} is now online.`);
});
});
I opened two separate browsers with two different logged in users to test, and when I refresh the page on one browser, the other gets the updated online user list in real-time, but the browser I initially refreshed on has an empty array for the user state. Do I need to make a global state store using redux or something?