Skip to content

Instantly share code, notes, and snippets.

@popuguytheparrot
Last active March 6, 2024 16:25
Show Gist options
  • Save popuguytheparrot/8422283696c35b4ac28ca900be4c05f6 to your computer and use it in GitHub Desktop.
Save popuguytheparrot/8422283696c35b4ac28ca900be4c05f6 to your computer and use it in GitHub Desktop.
websocket hook with effector
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];
}
@popuguytheparrot
Copy link
Author

popuguytheparrot commented May 30, 2019

export function App() {
  const [wsStatus, sendMessage] = useWebSocket('ws://localhost:8080', msg =>
    console.log(msg)
  );

  useEffect(() => {
    if (wsStatus === 'open') {
      sendMessage({ type: 'ready' });
    }
  }, [wsStatus]);
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment