-
-
Save Nimrockdev/2f22b729e2d0d956a0bd7c35be7285d4 to your computer and use it in GitHub Desktop.
Todo lo necesario para conectarnos a nuestro socket server - SocketContext, SocketProvider, useSocket
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 { createContext } from 'react'; | |
import { useSocket } from '../hooks/useSocket' | |
export const SocketContext = createContext(); | |
export const SocketProvider = ({ children }) => { | |
const { socket, online } = useSocket('http://localhost:8080'); | |
return ( | |
<SocketContext.Provider value={{ socket, online }}> | |
{ children } | |
</SocketContext.Provider> | |
) | |
} |
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 { useEffect, useMemo, useState } from 'react'; | |
import io from 'socket.io-client'; | |
export const useSocket = ( serverPath ) => { | |
const socket = useMemo(() => io.connect( serverPath, {transports: ['websocket']} ), [ serverPath ] ); | |
const [ online, setOnline ] = useState(false); | |
useEffect(() => { | |
setOnline( socket.connected ); | |
}, [socket]) | |
useEffect(() => { | |
socket.on('connect', () => setOnline( true )); | |
}, [ socket ]) | |
useEffect(() => { | |
socket.on('disconnect', () => setOnline( false )); | |
}, [ socket ]) | |
return { | |
socket, | |
online | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment