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]
JavaScript
x
111
111
1
const ShareTextComponentView = (props) => {
2
3
const [isShareMode, setShareMode] = useState(false)
4
const [syncText, setSyncText] = useState("")
5
const [isOpen, setOpen] = useState(false)
6
const [name, setName] = useState("")
7
8
let ws = null;
9
const connect = () => {
10
ws = new WebSocket(ADDRESS + `/${name}`)
11
12
//액세스코드들을 전부 보냄
13
ws.onopen = () => {
14
ws.send(JSON.stringify({command: "CONNECT", accessCode: generateAccessCode()}))
15
console.log(`${ADDRESS}에 접속 되었습니다.`)
16
setOpen(true)
17
}
18
19
ws.onclose = () => {
20
ws.send(JSON.stringify({command: "CLOSE"}))
21
console.log(`${ADDRESS}에 접속 종료 되었습니다.`)
22
setOpen(false)
23
}
24
25
ws.onmessage = (evt) => {
26
if (isShareMode) {
27
return
28
}
29
30
const message = JSON.parse(evt.data)
31
console.log({message: message})
32
setSyncText(message.data)
33
}
34
ws.onerror = (err) => {
35
console.log("접속중에 에러가 발생되었습니다.")
36
console.log(err)
37
}
38
}
39
40
const close = () => {
41
if (ws !== null && ws.readyState !== WebSocket.CLOSED) {
42
ws.close()
43
}
44
}
45
46
// p2p로 웹소켓으로 연결
47
useEffect(() => {
48
if (isOpen) {
49
return
50
}
51
52
connect()
53
setOpen(true)
54
55
return () => {
56
//만약 공유모드를 종료했을때 websocket에 shutdown 메세지를 보냄
57
if (isOpen) {
58
close()
59
console.log(`${ADDRESS}에 접속 종료 되었습니다.`)
60
}
61
setOpen(false)
62
}
63
64
}, [isShareMode])
65
66
const onTextInput = (text) => {
67
const {name, value} = text.target
68
69
if (!isShareMode) {
70
return
71
}
72
73
console.log("websocket status")
74
console.log(ws)
75
console.log("input value")
76
console.log(value)
77
if (ws.readyState === WebSocket.CLOSED) {
78
console.log("Connect Close 되었습니다.")
79
} else {
80
ws.send(JSON.stringify({command: "SEND", message: value}))
81
}
82
}
83
84
const generateAccessCode = () => {
85
return "hello"
86
}
87
88
89
const reconnect = () => {
90
connect()
91
console.log(ws)
92
}
93
return (
94
<div className="container">
95
<h1> Please Enter This Area Section</h1>
96
<h1> {isOpen ? "Connect" : "Disconnect"}</h1>
97
<div className="name-container">
98
<label> Name : </label>
99
<input type="text" onChange={(e) => {
100
setName(e.target.value)
101
}}/>
102
</div>
103
<button className="reconnect-mode" onClick={reconnect}>Connect</button>
104
<button className="is-receiever" onClick={() => setShareMode(!isShareMode)}>공유자 입니까?</button>
105
<h1>{isShareMode ? "공유모드" : "수신모드"}</h1>
106
<ShareTextComponent accessCode={generateAccessCode()} onInputEvent={onTextInput} syncText={syncText}/>
107
</div>
108
)
109
}
110
export default ShareTextComponentView;
111
[after logging in onTextInput]
Advertisement
Answer
Add a null check to the top of the function ->
JavaScript
1
3
1
const onTextInput = (text) => {
2
if (!ws) return;
3
This will at least help you get past that error and narrow down the rest of the flow.