-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
f649915
commit 049d29f
Showing
2 changed files
with
58 additions
and
35 deletions.
There are no files selected for viewing
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,45 @@ | ||
import { useEffect, useRef, useState } from 'react'; | ||
import { useSelector } from 'react-redux'; | ||
import connectionSelector from '../redux/selectors/connectionSelector'; | ||
|
||
const useWebSocket = () => { | ||
// eslint-disable-next-line no-unused-vars | ||
const [isOpen, setIsOpen] = useState(false); | ||
const clientObj = useSelector(connectionSelector.clientObj); | ||
const socket = useRef(null); | ||
|
||
useEffect(() => { | ||
// eslint-disable-next-line no-undef | ||
socket.current = new WebSocket( | ||
`ws://157.245.139.199:8080/bomb?token=${clientObj.ClientToken}` | ||
); | ||
socket.current.onopen = () => { | ||
setIsOpen(true); | ||
}; | ||
socket.current.onerror = (error) => { | ||
console.log('onerror', error); | ||
setIsOpen(false); | ||
}; | ||
|
||
return () => socket.current.close(); | ||
}, [clientObj, setIsOpen]); | ||
|
||
useEffect(() => { | ||
socket.current.onmessage = (msg) => { | ||
// console.log('onmessage', msg); | ||
const data = JSON.parse(msg.data); | ||
try { | ||
console.log(data); | ||
} catch (err) { | ||
// whatever you wish to do with the err | ||
console.log(err); | ||
} | ||
}; | ||
}, []); | ||
|
||
return [ | ||
socket | ||
]; | ||
}; | ||
|
||
export default useWebSocket; |
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