Last active
June 18, 2020 18:16
-
-
Save mikekoro/82fdc0690c1c0ee4436e793e24be0e62 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
// useSockets.js | |
import React, { | |
useState | |
} from 'react'; | |
import io from 'socket.io-client'; | |
export default function useSocket() { | |
const [Socket, setSocket] = useState(null); | |
const [notification, setNotification] = useState(''); | |
const [broadcast, setBroadcast] = useState(''); | |
const Connect = (token) => { | |
let socket = io.connect('wss://localhost:5001'); | |
socket.emit('authenticate', { | |
token: token | |
}).on('authenticated', (res) => { | |
window.socket = socket; | |
setSocket(socket); | |
}).on('notification', (data) => { | |
setNotification(data); | |
}).on('user_disconnected', (data) => { | |
setSocket(null); | |
}).on('broadcast', (data) => { | |
setBroadcast(data); | |
}); | |
} | |
const Disconnect = (socket) => { | |
socket.disconnect() | |
} | |
return { | |
Socket, | |
Connect, | |
Disconnect, | |
notification, | |
broadcast | |
}; | |
} | |
// Usage | |
const { Socket, Connect, Disconnect, notification, broadcast } = useSocket(); | |
useEffect(() => { | |
Connect(TOKEN); | |
},[]); | |
useEffect(() => { | |
if(Socket) { // We are connected! } | |
}, [Socket]); | |
useEffect(() => { | |
// Handle notifications events | |
}, [notification]); | |
useEffect(() => { | |
// Handle broadcast events | |
}, [broadcast]); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment