Created
October 29, 2020 21:48
-
-
Save jonasgroendahl/77b7d246b8186ae0c3248c6e26dcd74b to your computer and use it in GitHub Desktop.
useWebSockets()
This file contains 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 characters
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, | |
}; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment