Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
React Context used with Socket.io | Code from post: https://medium.com/@alexboots/using-react-context-with-socket-io-3b7205c86a6d
import React, { createContext } from "react";
const SocketContext = createContext({
queueLength: 0,
positionInLine: 0,
});
export default SocketContext;
import React, { useState, useEffect } from "react";
import SocketContext from "Components/socket_context/context";
import { initSockets } from "Sockets";
const SocketProvider = (props) => {
const [value, setValue] = useState({
queueLength: 0,
positionInLine: 0,
});
useEffect(() => initSockets({ setValue }), [initSockets]);
return(
<SocketContext.Provider value={ value }>
{ props.children }
</SocketContext.Provider>
)
};
export default SocketProvider;
/sockets
---index.js
---events.js
---emit.js
import React from "react";
import { render } from "react-dom";
import SocketProvider from "Components/socket_context";
import App from "Components/app";
const renderApp = App => {
render(
<SocketProvider>
<App/>
</SocketProvider>
document.getElementById("root")
);
}
renderApp(App);
import { socket } from "Sockets";
export const addClientToQueue = () => {
socket.emit('addClientIdToQueue');
};
export const getQueueLength = () => {
socket.emit('queueLengthToSocket');
};
export const removeUserFromQueue = () => {
socket.emit('removeUserFromQueue');
};
import { socket } from 'Sockets';
export const socketEvents = ({ setValue }) => {
socket.on('queueLength', ({ queueLength }) => {
setValue(state => { return { ...state, queueLength } });
});
socket.on('positionInLine', ({ positionInLine }) => {
setValue(state => { return { ...state, positionInLine } });
});
};
import io from "socket.io-client";
import { socketEvents } from "Sockets/events";
import { getQueueLength } from "Sockets/emit";
export const socket = io();
export const initSockets = ({ setValue }) => {
socketEvents({ setValue });
getQueueLength();
};
import React, { useContext } from "react";
import SocketContext from 'Components/socket_context/context'
const Lobby = props => {
const { positionInLine, queueLength } = useContext(SocketContext);
return (
<div>
yada
</div>
)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment