i want to send message while typing text by using websocket.
but have websocket reference error while typing text.
i think ShareTextComponent onInputEvent function parameter is not exeucte in another location.
so websocket property can’t reference in this field
but i don’t know how can i fix it.
and i didn’t use any state management library such as redux and mobx.
just pure reactjs
[error]
[code]
const ShareTextComponentView = (props) => { const [isShareMode, setShareMode] = useState(false) const [syncText, setSyncText] = useState("") const [isOpen, setOpen] = useState(false) const [name, setName] = useState("") let ws = null; const connect = () => { ws = new WebSocket(ADDRESS + `/${name}`) //액세스코드들을 전부 보냄 ws.onopen = () => { ws.send(JSON.stringify({command: "CONNECT", accessCode: generateAccessCode()})) console.log(`${ADDRESS}에 접속 되었습니다.`) setOpen(true) } ws.onclose = () => { ws.send(JSON.stringify({command: "CLOSE"})) console.log(`${ADDRESS}에 접속 종료 되었습니다.`) setOpen(false) } ws.onmessage = (evt) => { if (isShareMode) { return } const message = JSON.parse(evt.data) console.log({message: message}) setSyncText(message.data) } ws.onerror = (err) => { console.log("접속중에 에러가 발생되었습니다.") console.log(err) } } const close = () => { if (ws !== null && ws.readyState !== WebSocket.CLOSED) { ws.close() } } // p2p로 웹소켓으로 연결 useEffect(() => { if (isOpen) { return } connect() setOpen(true) return () => { //만약 공유모드를 종료했을때 websocket에 shutdown 메세지를 보냄 if (isOpen) { close() console.log(`${ADDRESS}에 접속 종료 되었습니다.`) } setOpen(false) } }, [isShareMode]) const onTextInput = (text) => { const {name, value} = text.target if (!isShareMode) { return } console.log("websocket status") console.log(ws) console.log("input value") console.log(value) if (ws.readyState === WebSocket.CLOSED) { console.log("Connect Close 되었습니다.") } else { ws.send(JSON.stringify({command: "SEND", message: value})) } } const generateAccessCode = () => { return "hello" } const reconnect = () => { connect() console.log(ws) } return ( <div className="container"> <h1> Please Enter This Area Section</h1> <h1> {isOpen ? "Connect" : "Disconnect"}</h1> <div className="name-container"> <label> Name : </label> <input type="text" onChange={(e) => { setName(e.target.value) }}/> </div> <button className="reconnect-mode" onClick={reconnect}>Connect</button> <button className="is-receiever" onClick={() => setShareMode(!isShareMode)}>공유자 입니까?</button> <h1>{isShareMode ? "공유모드" : "수신모드"}</h1> <ShareTextComponent accessCode={generateAccessCode()} onInputEvent={onTextInput} syncText={syncText}/> </div> ) } export default ShareTextComponentView;
[after logging in onTextInput]
Advertisement
Answer
Add a null check to the top of the function ->
const onTextInput = (text) => { if (!ws) return;
This will at least help you get past that error and narrow down the rest of the flow.