'React stat and Socket.io
I have this component in which I want to update a state and make an array with al the users connected in a room from an incoming msg from socket.on:
export default function ChatRoom() {
const [users, setUsers] = useState([]);
const { state } = useLocation(); //to get data from <Home/> component
socket.on("message", (msg) => console.log(msg));
useEffect(() => {
if (state.connected) {
socket.on("userconnected", (msg) => {
setUsers((old) => [...old, msg]);
console.log(state.username);
});
}
}, [state.connected, users]);
The username is coming from another component state in which I send a msg to the server:
export default function Home() {
const [username, setUsername] = useState("");
const [room, setRoom] = useState("");
const [connected, setConnected] = useState(false);
useEffect(() => {
if (connected && room && username) {
navigate("/chatroom", {
state: { username, room, connected },
});
}
}, [connected, room, username]);
const navigate = useNavigate();
const handleClick = (e) => {
e.preventDefault();
socket.emit("connected", username);
setConnected(true);
};
The problem is that I cant update the state with setUsers. I think it has to do with an async problem but I can´t figure it out. Basically I need an array with all the users that are connected.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
