-
-
Save codev0/044b0588caa79bf702599f94c1beefd3 to your computer and use it in GitHub Desktop.
websocket hook with effector
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, useCallback } from 'react'; | |
import { createEvent, createStore } from 'effector'; | |
import { useStore } from 'effector-react'; | |
const open = createEvent('open'); | |
const closed = createEvent('closed'); | |
const error = createEvent('error'); | |
const wsStatus = createStore('closed') | |
.on(open, () => 'open') | |
.on(closed, () => 'closed') | |
.on(error, () => 'error') | |
wsStatus.watch(state => console.log('ws', state)); | |
/** | |
* @param wsURL {String} | |
* @param onMessage {function} | |
* @param onError {function} | |
* @returns {[Object, function]} | |
*/ | |
export function useWebSocket(wsURL, onMessage, onError) { | |
const status = useStore(wsStatus); | |
const socketRef = useRef(); | |
function handleError(err) { | |
error(); | |
onError(err.message); | |
} | |
useEffect(() => { | |
const socket = new WebSocket(wsURL); | |
socketRef.current = socket; | |
socketRef.current.onopen = open; | |
socketRef.current.onclose = closed; | |
socketRef.current.onerror = handleError; | |
socketRef.current.onmessage = msg => onMessage(msg); | |
return () => { | |
socketRef.current.onopen = null; | |
socketRef.current.onclose = null; | |
socketRef.current.onmessage = null; | |
}; | |
}, []); | |
const sendMessage = useCallback( | |
message => { | |
socketRef.current.send(JSON.stringify(message)); | |
}, | |
[socketRef] | |
); | |
return [status, sendMessage]; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment