-
-
Save nomaanp/21fadbe4cfeb8c1b26f0943c5b3f285e to your computer and use it in GitHub Desktop.
useWebSockets()
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 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
how to import this hook to use it in defrent components