Skip to content

Instantly share code, notes, and snippets.

@johndavedecano
Created December 10, 2019 03:18
Show Gist options
  • Save johndavedecano/1cf05a7e9e7b42e03cb1174977fc166e to your computer and use it in GitHub Desktop.
Save johndavedecano/1cf05a7e9e7b42e03cb1174977fc166e to your computer and use it in GitHub Desktop.
Using socket io with ReactJS
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
import React from 'react'
import Button from 'components/Button'
import { useSocket } from './contexts/SocketContext'
const ButtonContainer = ({channelId}) => {
const socket = useSocket()
const handlePress = () => {
socket.emit('join_channel', { channelId })
}
return (
<Button onPress={handlePress}>
Join Channel
</Button>
)
}
export default ButtonContainer
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