Created
May 11, 2020 14:13
-
-
Save harmon25/e94bafe546002ad1379d2f6f8f3259fa to your computer and use it in GitHub Desktop.
phoenix socket react 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, {createContext, useContext, useEffect, useRef, useState} from "react" | |
import { Socket } from "phoenix"; | |
const SocketContext = createContext({socket: null, connected: false}) | |
const useSocketCtx = ()=> useContext(SocketContext) | |
// this is what you would use in child components to get access to the socket | |
export const useSocket = ()=> { | |
const {socket} = useSocketCtx() | |
return socket.current | |
} | |
// this should go in the child container, or in the app.js file - it cannot be invoked on the server. | |
export const SocketContext = ({children})=>{ | |
const [connected, setConnected] = useState(false) | |
const socket = useRef() | |
const setupSocket = ()=>{ | |
// can get away with relative url, as this should only run on the client.... | |
let phxSocket = new Socket("/socket", { | |
params: { token: "atoken?" }, | |
}); | |
// | |
phxSocket.onError( () => console.log("there was an error with the connection!") ) | |
phxSocket.onClose( () => setConnected(false) ) | |
phxSocket.connect(); | |
setConnected(true) | |
socket.current = phxSocket; | |
} | |
// this will run once on mount. | |
useEffect(setupSocket, []); | |
return (<SocketContext.Provider value={{socket: socket, connected }}> | |
{children} | |
</SocketContext.Provider>) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment