Skip to content

Instantly share code, notes, and snippets.

@LauraBeatris
Created July 21, 2020 16:08
Show Gist options
  • Save LauraBeatris/94424d852ff6315d1e88a5c6d0cf18a8 to your computer and use it in GitHub Desktop.
Save LauraBeatris/94424d852ff6315d1e88a5c6d0cf18a8 to your computer and use it in GitHub Desktop.
React Phoenix Socket Context
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;
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