Skip to content

Instantly share code, notes, and snippets.

@kianaditya
Last active July 20, 2020 08:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kianaditya/dcab4b49465813052febefbcf7c94310 to your computer and use it in GitHub Desktop.
Save kianaditya/dcab4b49465813052febefbcf7c94310 to your computer and use it in GitHub Desktop.
import React, { useState, useEffect } from 'react'
import socketIOClient from 'socket.io-client'
const socket = socketIOClient('http://localhost:3000', {
transports: ['websocket'],
autoConnect: false,
})
const App = () => {
const [connectionStatus, setConnectionStatus] = useState(false)
const [time, setTime] = useState([])
const [channel, setChannel] = useState()
useEffect(() => {
socket.on(channel, (data) => {
setTime((prev) => [data, ...prev])
})
}, [channel])
const handleSocket = () => {
socket.open()
socket.on('connect', () => {
setChannel(socket.connected ? socket.id : '')
})
}
const handleToggle = () => {
socket.connected ? socket.close() : handleSocket()
setConnectionStatus((prev) => !prev)
setTime([])
}
return (
<div>
{connectionStatus ? 'Connected to ' + channel : 'Disconnected'}
<br />
<button onClick={handleToggle}>
{' '}
{connectionStatus ? 'Disconnect' : 'Connect'}
</button>
<div>{time && time.map((entry) => <p key={entry}>{entry}</p>)}</div>
</div>
)
}
export default App
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment