Skip to content

Instantly share code, notes, and snippets.

@harmon25
Created May 11, 2020 14:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save harmon25/e94bafe546002ad1379d2f6f8f3259fa to your computer and use it in GitHub Desktop.
Save harmon25/e94bafe546002ad1379d2f6f8f3259fa to your computer and use it in GitHub Desktop.
phoenix socket react context
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