-
-
Save xiCO2k/cfbfafc588ecb1a1a97f1ba8a533cc8d to your computer and use it in GitHub Desktop.
Revisions
-
jonasgroendahl created this gist
Oct 29, 2020 .There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,66 @@ import {useEffect, useRef, useState} from 'react'; import io from 'socket.io-client'; type Props = { userId: number; enabled: boolean; onConnected?: () => void; }; type Message = { content: string; senderId: string; userId: string; date: Date; }; const useWebSockets = ({userId, enabled, onConnected}: Props) => { const ref = useRef<SocketIOClient.Socket>(); const [messages, setMessages] = useState<Message[]>([]); const send = (msg: string, senderId: number) => { ref.current!.emit('message', { content: msg, senderId: senderId, userId, date: new Date(), }); }; useEffect(() => { if (!enabled) { return; } const socket = io('localhost:3000'); socket.emit('joinRoom', userId); socket.emit('message', (msg: Message) => { setMessages((prev) => prev.concat(msg)); }); socket.on('disconnect', () => { console.log('disconnected'); }); socket.on('connect', () => { if (onConnected) { onConnected(); } }); socket.on('reconnect', () => { socket.emit('joinRoom', userId); }); ref.current = socket; return () => socket.disconnect(); }, [enabled, userId]); return { send, messages, }; };