On frontend(reactjs) I have form for submitting the data before joining the room, since data has to be validated, I have onSubmit function that does that and if everything is ok redirects the user to /drawing-page
, when that happens socket disconnects(socket.on('disconnect') triggers on backend).
import { io } from 'socket.io-client';
const socket = io('http://localhost:8080');
export const formValidation = (username, room) => {
if (!username || !room) {
alert('Room and username must be provided');
return false;
}
if (username.length < 4 || room.length < 4) {
alert('Room and username must be at least 4 characters long');
return false;
}
if (username.length > 30 || room.length > 30) {
alert('Room and username can\'t be longer than 30 characters');
return false;
}
return true;
}
const onSubmit = e => {
e.preventDefault();
const username = e.target.username.value;
const room = e.target.room.value;
if (!formValidation(username, room)) {
return;
}
socket.emit('join', { username, room }, error => {
if (error) {
alert(error);
window.location.href = '/';
}
});
window.location.href = '/drawing-page';
}
Backend code:
socket.on('disconnect', reason => {
console.log(`reason: ${reason}`);
const user = removeUser(socket.id);
if (user) {
if (!io.sockets.adapter.rooms.get(user.room)) {
removeRoom(user.room);
io.emit('showActiveRooms', getRooms());
}
}
});
Because of URL change, socket disconnects, is there any way that I can make socket disconnect only when app closes and not when url changes