mirror of
https://github.com/randyjc/Rahoot.git
synced 2026-03-14 04:25:35 +01:00
First Commit
This commit is contained in:
51
src/context/player.jsx
Normal file
51
src/context/player.jsx
Normal file
@@ -0,0 +1,51 @@
|
||||
import { createContext, useContext, useReducer } from "react"
|
||||
|
||||
export const PlayerContext = createContext()
|
||||
|
||||
export function playerReducer(state, action) {
|
||||
switch (action.type) {
|
||||
case "JOIN":
|
||||
return { player: { ...state.player, room: action.payload } }
|
||||
case "LOGIN":
|
||||
return {
|
||||
player: {
|
||||
...state.player,
|
||||
username: action.payload,
|
||||
points: 0,
|
||||
},
|
||||
}
|
||||
case "UPDATE":
|
||||
return { player: { ...state.player, ...action.payload } }
|
||||
case "LOGOUT":
|
||||
return { player: null }
|
||||
default:
|
||||
return state
|
||||
}
|
||||
}
|
||||
|
||||
export const PlayerContextProvider = ({ children }) => {
|
||||
const [state, dispatch] = useReducer(playerReducer, {
|
||||
player: null,
|
||||
})
|
||||
|
||||
return (
|
||||
<PlayerContext.Provider
|
||||
value={{
|
||||
...state,
|
||||
dispatch,
|
||||
}}
|
||||
>
|
||||
{children}
|
||||
</PlayerContext.Provider>
|
||||
)
|
||||
}
|
||||
|
||||
export function usePlayerContext() {
|
||||
const context = useContext(PlayerContext)
|
||||
|
||||
if (!context) {
|
||||
throw Error("usePlayerContext must be used inside an PlayerContextProvider")
|
||||
}
|
||||
|
||||
return context
|
||||
}
|
||||
24
src/context/socket.jsx
Normal file
24
src/context/socket.jsx
Normal file
@@ -0,0 +1,24 @@
|
||||
import { io } from "socket.io-client"
|
||||
import { createContext, useContext, useState } from "react"
|
||||
import { WEBSOCKET_URL } from "@/constants"
|
||||
|
||||
export const socket = io("http://localhost:5057", {
|
||||
path: "/ws/",
|
||||
//addTrailingSlash: false,
|
||||
transports: ["websocket"],
|
||||
})
|
||||
|
||||
export const SocketContext = createContext()
|
||||
|
||||
export const SocketContextProvider = ({ children }) => {
|
||||
return (
|
||||
<SocketContext.Provider value={socket}>{children}</SocketContext.Provider>
|
||||
)
|
||||
}
|
||||
|
||||
export function useSocketContext() {
|
||||
const context = useContext(SocketContext)
|
||||
const [isConnected, setIsConnected] = useState(false)
|
||||
|
||||
return { socket: context }
|
||||
}
|
||||
Reference in New Issue
Block a user