Created
December 10, 2019 03:18
-
-
Save johndavedecano/1cf05a7e9e7b42e03cb1174977fc166e to your computer and use it in GitHub Desktop.
Using socket io with ReactJS
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 from 'react' | |
import { Provider } from 'react-redux' | |
import Root from './root' | |
import { SocketProvider } from './contexts/SocketContext' | |
const App = () => { | |
return ( | |
<Provider store={store}> | |
<SocketProvider store={store}> | |
<Root /> | |
</SocketProvider> | |
</Provider> | |
) | |
} | |
export default App |
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, { | |
createContext, | |
useContext, | |
useRef, | |
useEffect, | |
useState, | |
} from 'react' | |
import io from 'socket.io-client' | |
export const SocketContext = createContext() | |
export const SocketProvider = ({ children, store }) => { | |
const [isConnected, setConnected] = useState(false) | |
const socketUrl = `${process.env.API_URL}/socket.io` | |
const socket = useRef(null) | |
const handleOnMessage = message => { | |
console.log(message) | |
// store.dispatch here | |
} | |
useEffect(() => { | |
if (!isConnected) { | |
socket.current = io(socketUrl, { | |
transports: ['websocket'], | |
query: { | |
token: localStorage.getItem('auth_token'), | |
}, | |
}) | |
socket.current.on('connect', () => { | |
console.info(`Successfully connected to socket at ${socketUrl}`) | |
setConnected(true) | |
}) | |
socket.current.on('disconnect', () => { | |
console.info(`Successfully disconnected`) | |
setConnected(false) | |
}) | |
socket.current.on('error', err => { | |
console.log('Socket Error:', err.message) | |
}) | |
socket.current.on('message', handleOnMessage) | |
} | |
return () => { | |
if (socket.current && socket.current.connected) { | |
socket.current.disconnect() | |
} | |
} | |
}, []) | |
return ( | |
<SocketContext.Provider value={socket.current}> | |
{children} | |
</SocketContext.Provider> | |
) | |
} | |
export const useSocket = () => useContext(SocketContext) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment