/
lizardking
/
react_project
Обзор
Документация
Войти
/
lizardking
/
react_project
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
0
CI/CD
Аналитика
Безопасность
master
src/features/refExample/model/useWebSocketLogger.ts
33 строки
1 KB
LizardKing
Task 5 - useRef
17 окт 2025, 03:34
17 окт 2025, 03:34
e989e42
Код
Авторство
О чём код?
import { useEffect, useRef } from 'react' export function useWebSocketLogger(url: string) { const socketRef = useRef<WebSocket | null>(null) useEffect(() => { const socket = new WebSocket(url) socketRef.current = socket socket.onopen = () => // eslint-disable-next-line no-console console.log(`WS open → ${url}`) socket.onmessage = (event) => // eslint-disable-next-line no-console console.log(`WS message: ${String(event.data).slice(0, 200)}`) socket.onerror = () => // eslint-disable-next-line no-console console.log('WS error') socket.onclose = (event) => // eslint-disable-next-line no-console console.log(`WS close ${event.code} ${event.reason || '—'}`) return () => socket.close(1000, 'unmount') }, [url]) return { send: (message: string) => socketRef.current?.readyState === WebSocket.OPEN ? socketRef.current.send(message) // eslint-disable-next-line no-console : console.log('WS not open'), } }