Use jotai for websocket
All checks were successful
continuous-integration/drone/push Build is passing
All checks were successful
continuous-integration/drone/push Build is passing
This commit is contained in:
parent
f3e6699ca5
commit
cc1808c9ec
|
@ -1,5 +1,5 @@
|
|||
import { atom, useAtom } from 'jotai'
|
||||
import { useCallback, useState } from 'react'
|
||||
import { useCallback } from 'react'
|
||||
|
||||
const roomNameAtom = atom(getRoomNameFromUrl())
|
||||
|
||||
|
|
|
@ -1,19 +1,19 @@
|
|||
import { useCallback, useState } from 'react'
|
||||
import { atom, useAtom } from 'jotai'
|
||||
import { useCallback, useEffect } from 'react'
|
||||
import { WEBSOCKET_URL } from '../background/constants'
|
||||
import { UserInfo } from '../components/jitsi/types'
|
||||
|
||||
const createWebSocketConnection = (userInfo: UserInfo) => {
|
||||
const webSocket = new WebSocket(WEBSOCKET_URL)
|
||||
console.log('[Rooms] createWebSocketConnection')
|
||||
webSocket.addEventListener('open', (_: Event) => webSocket.send(JSON.stringify(userInfo)))
|
||||
|
||||
return webSocket
|
||||
}
|
||||
const webSocket = new WebSocket(WEBSOCKET_URL)
|
||||
const webSocketConnectionAtom = atom(webSocket)
|
||||
|
||||
function useWebSocketConnection(userInfo: UserInfo) {
|
||||
console.log('[Rooms] useWebSocketConnection')
|
||||
|
||||
const [webSocketConnection] = useState<WebSocket>(() => createWebSocketConnection(userInfo))
|
||||
const [webSocketConnection] = useAtom(webSocketConnectionAtom)
|
||||
useEffect(() => {
|
||||
sendMessageNowOrLater(webSocketConnection, JSON.stringify(userInfo))
|
||||
}, [webSocketConnection, userInfo]);
|
||||
|
||||
const sendMessage = useCallback(
|
||||
(message: string) => {
|
||||
|
@ -41,4 +41,11 @@ function useWebSocketConnection(userInfo: UserInfo) {
|
|||
return { onMessage, sendMessage, disconnect }
|
||||
}
|
||||
|
||||
const sendMessageNowOrLater = (webSocket: WebSocket, message: string) => {
|
||||
if (webSocket.readyState !== WebSocket.OPEN) {
|
||||
return webSocket.addEventListener('open', (_: Event) => webSocket.send(message))
|
||||
}
|
||||
webSocket.send(message)
|
||||
}
|
||||
|
||||
export default useWebSocketConnection
|
||||
|
|
Loading…
Reference in a new issue