import * as React from 'react';
import { SocketContext } from '@/contexts/socketContext';
/**
 *
 * @param channel 데이터 수신시 핸들러를 등록할 수신할 소켓 채널이름
 * @param onReceive 데이터 수신시 실행되는 이벤트 핸들러 함수
 * @returns null
 * @example
 * useSocketReceive('hello', (payload) => {
 *   console.log(payload);
 * }); // 'hello' 채널에 이벤트 발생시 받은 payload를 콘솔에 출력함
 */
function useSocketReceive(channel: string, onReceive: (...payload: any[]) => void) {
  const { connection } = React.useContext(SocketContext);
  // 해당 훅을 사용한 컴포넌트가 마운트되면 이벤트 핸들러를 등록, 언마운트되면 제거함
  React.useEffect(() => {
    connection.on(channel, (payload) => {
      onReceive(payload);
    });
    return () => {
      connection.off(channel, onReceive);
    };
  }, []);
}
export default useSocketReceive;
channel
onReceive
connection.on(channel, (...payload) => { ... } 또는 onReceive(...payload)로 수정예정없음
import * as React from 'react';
import useSocketReceive from '@/lib/hooks/useSocketReceive';
const Label = () => {
	const [label, setLabel] = React.useState('');
	useSocketReceive('hello', (payload: string) => {
		setLabel(payload);
	}
	return <div>{label}</div>;
};
export default Label;
import * as React from 'react';
import { SocketContext } from '@/contexts/socketContext';
/**
 *
 * @param channel 데이터를 전송할 소켓 채널이름
 * @returns 파라미터로 전달한 데이터를 channel로 전송해주는 함수
 * @example
 * const helloEmit = useSocketSend('hello');
 * ...
 * helloEmit('hello world!'); // hello 채널로 'hello world' 문자열을 전송
 */
function useSocketSend(channel: string) {
  const { connection } = React.useContext(SocketContext);
  // emit(1, 2, 3) 과 emit([1, 2, 3]) 이 동일한 기능을 하기 위한 로직
  return (...dataToEmit: any[]) => {
    connection.emit(channel, dataToEmit.length ? dataToEmit[0] : dataToEmit);
  };
}
export default useSocketSend;