File tree Expand file tree Collapse file tree 1 file changed +18
-27
lines changed Expand file tree Collapse file tree 1 file changed +18
-27
lines changed Original file line number Diff line number Diff line change 1
1
import React , { useEffect , useState } from 'react'
2
2
import ReactDOM from 'react-dom'
3
3
4
+ // const socket = new WebSocket()
4
5
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
11
11
12
12
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 ) )
24
17
}
25
- } , [ count ] )
26
-
27
- const handleClick = _ => {
28
- setCount ( count + 1 )
29
- }
18
+ } , [ socket ] )
30
19
31
20
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 >
35
23
</ div >
36
24
}
37
25
26
+
38
27
const App = ( ) => {
39
- return < div > Hello world again.
40
- < Timer className = 'my-timer' />
28
+ return < div > App
29
+
30
+ < MyWebSocket />
31
+
41
32
</ div >
42
33
}
43
34
You can’t perform that action at this time.
0 commit comments