Skip to content

Instantly share code, notes, and snippets.

@StoneyEagle
Created August 15, 2022 20:17
Show Gist options
  • Save StoneyEagle/df83b83e11627c89730010265455a255 to your computer and use it in GitHub Desktop.
Save StoneyEagle/df83b83e11627c89730010265455a255 to your computer and use it in GitHub Desktop.
import React, { createContext, useContext, useEffect, useState } from 'react';
import io, { Socket } from 'socket.io-client';
import { useSelector, useStore } from 'react-redux';
import SocketEvents from './SocketEvents';
export const SocketContext = createContext();
export const useSocket = () => useContext(SocketContext);
export const SocketProvider = ({ children }) => {
const [socket, setSocket] = useState();
const serverUrl = 'https://yourUrl.com';
const conOpts: Partial<ManagerOptions & SocketOptions> = {
extraHeaders: {
Authorization: `bearer ${userAccessToken ? userAccessToken : ''}`,
cors: '*',
},
forceNew: true,
reconnectionDelay: 1000,
reconnectionDelayMax: 5000,
reconnectionAttempts: Infinity,
timeout: 1000,
transports: ['polling', 'websocket'],
reconnection: true,
};
const store = useStore();
useEffect(() => {
let newSocket = io(serverUrl, conOpts);
setSocket(newSocket);
return () => {
socket.disconnect();
}
}, []);
return (
<SocketContext.Provider value={socket}>
{socket && <SocketEvents socket={socket} />} // component that has all the event listeners and killers
{children}
</SocketContext.Provider>
);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment