Skip to content

Instantly share code, notes, and snippets.

@mikekoro
Last active June 18, 2020 18:16
Show Gist options
  • Save mikekoro/82fdc0690c1c0ee4436e793e24be0e62 to your computer and use it in GitHub Desktop.
Save mikekoro/82fdc0690c1c0ee4436e793e24be0e62 to your computer and use it in GitHub Desktop.
// 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