Answer the question
In order to leave comments, you need to log in
How to properly organize work with socket.io in SPA with and without connection to rooms?
Good afternoon.
In a SPA application, I connect the user to the socket as soon as he is authorized
useEffect(() => {
if (isAuth) {
dispatch(
SocketActionCreators.setSocket(
io(API_URL, {
transports: ['websocket'],
path: '/server',
})
)
);
} else if (socket && !isAuth) {
socket.disconnect();
}
}, [isAuth]);
useEffect(() => {
if (socket) {
socket.emit('user:join-webinar', { user, webinarId });
socket.on('users:get', (rosters) => {
dispatch(CurrentWebinarActionCreators.setRosters(rosters));
});
socket.emit('message:get', webinarId);
socket.on('messages', (messages) => {
dispatch(CurrentWebinarActionCreators.setMessages(messages));
});
socket.on('chat:status', (status) => {
dispatch(CurrentWebinarActionCreators.setChatIsAvailable(status));
});
return () => {
socket.emit('user:left-webinar', { user, webinarId });
};
}
}, [webinarId, socket]);
// переменная для предотвращения показа сообщения о восстановлении связи
// при первом подключении
let firstConnection = true;
socket.on('connect', () => {
if (!firstConnection) {
message.success({
content: 'Связь восстановлена',
key: 'updatable',
duration: 2,
});
}
});
socket.on('disconnect', () => {
firstConnection = false;
message.error({
content: 'Потеря соединения',
key: 'updatable',
duration: 2,
}).then(() =>
message.loading({
content: 'Пытаемся восстановить подключение...',
key: 'updatable',
duration: 0,
})
);
});
Answer the question
In order to leave comments, you need to log in
If it helps someone, the answer to the 2nd question:
you can restore communication with the room when reconnecting by simply placing an emit on the join request inside the connect handler
socket.on('connect', () => {
socket.emit('user:join-webinar', { user, webinarId });
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question