Last active
March 6, 2024 16:25
-
-
Save popuguytheparrot/8422283696c35b4ac28ca900be4c05f6 to your computer and use it in GitHub Desktop.
websocket hook with effector
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
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]; | |
} |
Author
popuguytheparrot
commented
May 30, 2019
•
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment