Fix double chat messages with useEffect cleanup
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
b8c7b4b954
commit
bc88f79fef
|
@ -7,20 +7,22 @@ import useWebSocketConnection from './useWebSocketConnection'
|
||||||
function useBackendData(userInfo: UserInfo) {
|
function useBackendData(userInfo: UserInfo) {
|
||||||
console.log('[Rooms] useBackendData')
|
console.log('[Rooms] useBackendData')
|
||||||
|
|
||||||
const { onMessage, sendMessage, disconnect } = useWebSocketConnection(userInfo)
|
const { onMessage, cleanUpOnMessage, sendMessage, disconnect } = useWebSocketConnection(userInfo)
|
||||||
const { roomData, setRoomData } = useRoomData()
|
const { roomData, setRoomData } = useRoomData()
|
||||||
const { addChatMessage } = useAllChat()
|
const { addChatMessage } = useAllChat()
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
console.log('[Rooms] add onMessage Listener')
|
console.log('[Rooms] add onMessage Listener')
|
||||||
onMessage((messageString) => {
|
const messageCallback = (messageString: string) => {
|
||||||
console.log('[Rooms] message from ws', messageString)
|
console.log('[Rooms] message from ws', messageString)
|
||||||
const messageObject = JSON.parse(messageString)
|
const messageObject = JSON.parse(messageString)
|
||||||
|
|
||||||
!!messageObject.roomsData && setRoomData(messageObject)
|
!!messageObject.roomsData && setRoomData(messageObject)
|
||||||
!!messageObject.content && addChatMessage(messageObject)
|
!!messageObject.content && addChatMessage(messageObject)
|
||||||
return disconnect
|
return disconnect
|
||||||
})
|
}
|
||||||
|
onMessage(messageCallback)
|
||||||
|
return () => cleanUpOnMessage(messageCallback)
|
||||||
}, [])
|
}, [])
|
||||||
|
|
||||||
return { roomData, sendMessage }
|
return { roomData, sendMessage }
|
||||||
|
|
|
@ -37,8 +37,12 @@ function useWebSocketConnection(userInfo: UserInfo) {
|
||||||
)
|
)
|
||||||
|
|
||||||
const disconnect = useCallback(webSocketConnection.close, [webSocketConnection])
|
const disconnect = useCallback(webSocketConnection.close, [webSocketConnection])
|
||||||
|
const cleanUpOnMessage = useCallback((callbackToRemove: any) => {
|
||||||
|
console.log('[Rooms] cleanUpOnMessage')
|
||||||
|
webSocketConnection.removeEventListener('message', callbackToRemove)
|
||||||
|
}, [webSocketConnection])
|
||||||
|
|
||||||
return { onMessage, sendMessage, disconnect }
|
return { onMessage, cleanUpOnMessage, sendMessage, disconnect }
|
||||||
}
|
}
|
||||||
|
|
||||||
export default useWebSocketConnection
|
export default useWebSocketConnection
|
||||||
|
|
Loading…
Reference in a new issue