Last active
January 24, 2022 07:51
-
-
Save StoneyEagle/ddd4b6e545bbd15113ff0e50ff991487 to your computer and use it in GitHub Desktop.
React SocketProvider
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, { useState } from 'react'; | |
import { useSocket } from "./constext/SocketProvider"; | |
function App() { | |
const socket = useSocket(); | |
const [data, setData] = useState([]); | |
useEffect(() => { | |
if (socket) { | |
socket.on('message', (res) => { | |
setData(currentData => [...curentData, res]); | |
}); | |
} | |
},[socket]); | |
return ( | |
<> | |
<p>{JSON.stringify(data)}</p> | |
</> | |
); | |
} | |
export default App; |
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, { useState } from 'react'; | |
import { SocketProvider } from './contexts/SocketProvider'; | |
ReactDOM.render( | |
<SocketProvider socket={socket} setSocket={setSocket}> | |
<App /> | |
</SocketProvider>, | |
document.getElementById('root'), | |
); |
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, { useContext, useEffect, useState } from 'react'; | |
import io from 'socket.io-client'; | |
const SocketContext = React.createContext(); | |
const location = 'loalhost:3000'; | |
const [socket, setSocket] = useState(); | |
export function useSocket() { | |
return useContext(SocketContext); | |
} | |
export function SocketProvider({ children }) { | |
let conOpts = { | |
extraHeaders: { | |
cors: { | |
origin: '*', | |
methods: 'GET,PUT,POST,DELETE,OPTIONS'.split(','), | |
credentials: true | |
}, | |
}, | |
cors_allowed_origins: '*', | |
reconnect: true, | |
reconnectDelay: 1000, | |
reconnectDelayMax: 5000, | |
reconnectAttempts: Infinity, | |
timeout: 1000, | |
transports: [ | |
'polling', | |
'websocket' | |
], | |
'reconnection limit': 3000, | |
'max reconnection attempts': Number.MAX_VALUE, | |
'connect timeout': 7000, | |
'force new connection': true | |
}; | |
useEffect(() => { | |
let newSocket; | |
let timeout; | |
if (location) { | |
newSocket = io(location, conOpts); | |
setSocket(newSocket); | |
} | |
return () => { | |
newSocket?.close(); | |
}; | |
}, [location]); | |
return ( | |
<SocketContext.Provider value={ socket } > | |
{ children } | |
</SocketContext.Provider> | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment