refactor: useSocket

This commit is contained in:
cha0s 2020-12-13 04:49:23 -06:00
parent 6b5fbd540c
commit 14a6b80a44
2 changed files with 49 additions and 54 deletions

View File

@ -28,7 +28,8 @@ export default function Chat() {
const hasChannel = !!useSelector((state) => channelSelector(state, channel));
const historyLength = useSelector(historyLengthSelector);
const renderedChannel = renderChannel(channel);
useSocket((socket) => {
const socket = useSocket();
useEffect(() => {
let handle;
const load = throttle(async () => {
setActivity(await socket.send(['Activity']));
@ -41,7 +42,7 @@ export default function Chat() {
clearInterval(handle);
}
};
}, [channel]);
}, [channel, socket]);
const isAllowed = user.id > 0 || !!channel;
useEffect(() => {
if (!isAllowed) {

View File

@ -1,6 +1,6 @@
import {useDispatch, useSelector} from 'react-redux';
import {useSocket} from '@latus/socket/client';
import {useSocketPacket} from '@latus/socket/client';
import {
addMessage,
joined,
@ -20,58 +20,52 @@ import {
export default function Dispatcher() {
const dispatch = useDispatch();
const id = useSelector(idSelector);
useSocket((socket) => {
const onPacket = (packet) => {
switch (packet.constructor.name) {
case 'AddFriend': {
const {adderId, addeeId, name} = packet.data;
dispatch(addFriendship({
addeeId,
adderId,
status: 'pending',
}));
dispatch(setUsernames({[id === adderId ? addeeId : adderId]: name}));
break;
}
case 'Block': {
dispatch(block(packet.data));
break;
}
case 'ConfirmFriend': {
dispatch(confirmFriendship(packet.data));
break;
}
case 'Message': {
dispatch(addMessage(packet.data));
break;
}
case 'Join': {
dispatch(joined(packet.data));
break;
}
case 'Leave': {
dispatch(left(packet.data));
break;
}
case 'RemoveFriend': {
dispatch(removeFriendship(packet.data));
break;
}
case 'RemoveFavorite': {
dispatch(removeFromFavorites(packet.data));
break;
}
case 'Unblock': {
dispatch(unblock(packet.data));
break;
}
default:
useSocketPacket((packet) => {
switch (packet.constructor.name) {
case 'AddFriend': {
const {adderId, addeeId, name} = packet.data;
dispatch(addFriendship({
addeeId,
adderId,
status: 'pending',
}));
dispatch(setUsernames({[id === adderId ? addeeId : adderId]: name}));
break;
}
};
socket.on('packet', onPacket);
socket.on('disconnect', () => socket.off('packet', onPacket));
socket.on('reconnect', () => socket.on('packet', onPacket));
return () => socket.off('packet', onPacket);
case 'Block': {
dispatch(block(packet.data));
break;
}
case 'ConfirmFriend': {
dispatch(confirmFriendship(packet.data));
break;
}
case 'Message': {
dispatch(addMessage(packet.data));
break;
}
case 'Join': {
dispatch(joined(packet.data));
break;
}
case 'Leave': {
dispatch(left(packet.data));
break;
}
case 'RemoveFriend': {
dispatch(removeFriendship(packet.data));
break;
}
case 'RemoveFavorite': {
dispatch(removeFromFavorites(packet.data));
break;
}
case 'Unblock': {
dispatch(unblock(packet.data));
break;
}
default:
}
}, []);
return null;
}