Created
November 25, 2022 21:29
-
-
Save GuilhermeSantos001/79a90e574fccaee58bd3c47fc5787382 to your computer and use it in GitHub Desktop.
Socket Provider
This file contains hidden or 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, useEffect, useState } from 'react' | |
| import { io } from 'socket.io-client' | |
| import { useSelector } from 'react-redux' | |
| const SocketContext = createContext({ socket: null }) | |
| const SocketProvider = (props) => { | |
| const [socket, setSocket] = useState(null) | |
| const { userData } = useSelector((state) => state.user) | |
| useEffect(() => { | |
| if (!socket && userData) | |
| setSocket( | |
| io(process.env.REACT_APP_API_CHAT_SOCKETIO, { | |
| auth: { token: `Bearer ${userData.token}` } | |
| }) | |
| ) | |
| if (socket && !socket.connected) socket.connect() | |
| return () => { | |
| if (socket) socket.disconnect() | |
| } | |
| }, [socket, userData]) | |
| return ( | |
| <SocketContext.Provider value={socket}> | |
| {props.children} | |
| </SocketContext.Provider> | |
| ) | |
| } | |
| function useSocket() { | |
| const socket = useContext(SocketContext) | |
| return socket | |
| } | |
| export { SocketProvider, useSocket } | |
| export default SocketContext |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment