Skip to content

Commit 08027f9

Browse files
17 - MyWebSocket React Component
1 parent 0733f54 commit 08027f9

File tree

1 file changed

+18
-27
lines changed

1 file changed

+18
-27
lines changed

index.js

Lines changed: 18 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -1,43 +1,34 @@
11
import React, {useEffect, useState} from 'react'
22
import ReactDOM from 'react-dom'
33

4+
// const socket = new WebSocket()
45

5-
const Timer = (props) =>{
6-
const [count, setCount] = useState(-1)
7-
console.log(count, props)
8-
useEffect(()=>{
9-
// lookup to api service
10-
}, [])
6+
const MyWebSocket = () => {
7+
const [socket, setSocket] = useState(null)
8+
// 1. connect to the websocket server
9+
// 2. push & listen for messages in the websocket connection
10+
// 3. disconnect from websocket server
1111

1212
useEffect(()=>{
13-
// console.log("mounted")
14-
// setCount(count+1)
15-
let myTimer;
16-
if (count > 10) {
17-
myTimer = setTimeout(()=>{
18-
setCount(count + 1)
19-
}, 1000)
20-
}
21-
22-
return () => {
23-
clearTimeout(myTimer)
13+
// connect to the websocket server
14+
if (socket === null) {
15+
const wsURI = 'ws://localhost:8765'
16+
setSocket(new WebSocket(wsURI))
2417
}
25-
}, [count])
26-
27-
const handleClick = _ => {
28-
setCount(count + 1)
29-
}
18+
}, [socket])
3019

3120
return <div>
32-
33-
<h1>Timer - {count}</h1>
34-
<button onClick={handleClick}>Reset</button>
21+
<h1>WebSocket</h1>
22+
<p>{socket && socket.readyState === WebSocket.CONNECTING ? "Connecting" : "other"} </p>
3523
</div>
3624
}
3725

26+
3827
const App = () => {
39-
return <div>Hello world again.
40-
<Timer className='my-timer' />
28+
return <div>App
29+
30+
<MyWebSocket />
31+
4132
</div>
4233
}
4334

0 commit comments

Comments
 (0)