Created
July 21, 2020 16:08
-
-
Save LauraBeatris/94424d852ff6315d1e88a5c6d0cf18a8 to your computer and use it in GitHub Desktop.
React Phoenix Socket Context
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, { useEffect, useMemo } from "react"; | |
import { Socket } from "phoenix"; | |
// A utility to get the JWT token of the user | |
import getUserJWT from "utils/getUserJWT"; | |
// The URL of the socket, example: ws://localhost:4000 | |
import { SOCKET_URL } from "settings/socket"; | |
// A hook that returns the current user authenticated | |
import { useCurrentUser } from "contexts/currentUser/CurrentUserContext"; | |
import { SocketProvider } from "./SocketContext"; | |
const SocketContainer = ({ children }) => { | |
const [currentUser] = useCurrentUser(); | |
const socket = useMemo(() => ( | |
new Socket(SOCKET_URL, { | |
params: () => ({ | |
Authorization: getUserJWT(), | |
}), | |
}) | |
), []); | |
useEffect(() => { | |
if (currentUser && !socket.isConnected()) { | |
socket.connect(); | |
} | |
}, [ | |
socket, | |
currentUser, | |
]); | |
return ( | |
<SocketProvider value={socket}> | |
{children} | |
</SocketProvider> | |
); | |
}; | |
export default SocketContainer; |
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"; | |
const SocketContext = React.createContext({}); | |
export const SocketProvider = SocketContext.Provider; | |
export const useSocket = () => React.useContext(SocketContext); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment