-
-
Save wdwang09/931347966471780437a5d0288269a1d7 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, { useState, useEffect } from 'react'; | |
import logo from './logo.svg'; | |
import './App.css'; | |
import io from 'socket.io-client'; | |
const socket = io('localhost:3001'); | |
function App() { | |
const [isConnected, setIsConnected] = useState(socket.connected); | |
const [lastMessage, setLastMessage] = useState(null); | |
useEffect(() => { | |
// CONSOLE LOG HERE | |
console.log('useEffect'); | |
socket.on('connect', () => { | |
setIsConnected(true); | |
}); | |
socket.on('disconnect', () => { | |
setIsConnected(false); | |
}); | |
socket.on('message', data => { | |
setLastMessage(data); | |
}); | |
return () => { | |
// CONSOLE LOG HERE | |
console.log('useEffect return'); | |
socket.off('connect'); | |
socket.off('disconnect'); | |
socket.off('message'); | |
}; | |
}, []); // CHANGE | |
const sendMessage = () => { | |
socket.emit('hello!'); | |
} | |
return ( | |
<div className="App"> | |
<header className="App-header"> | |
<img src={logo} className="App-logo" alt="logo" /> | |
<p>Connected: { '' + isConnected }</p> | |
<p>Last message: { lastMessage || '-' }</p> | |
<button onClick={ sendMessage }>Say hello!</button> | |
<p> | |
Edit <code>src/App.js</code> and save to reload. | |
</p> | |
<a | |
className="App-link" | |
href="https://reactjs.org" | |
target="_blank" | |
rel="noopener noreferrer" | |
> | |
Learn React | |
</a> | |
</header> | |
</div> | |
); | |
} | |
export default App; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment