2021-02-05 21:32:38 -05:00
|
|
|
import React, { useState, useEffect, useContext } from "react";
|
2021-06-03 01:31:18 -04:00
|
|
|
import Session from "../network/Session";
|
2020-12-31 01:56:51 -05:00
|
|
|
|
2021-07-16 00:55:33 -04:00
|
|
|
import { PartyState } from "../types/PartyState";
|
|
|
|
|
2021-06-03 01:31:18 -04:00
|
|
|
const PartyContext = React.createContext<PartyState | undefined>(undefined);
|
2020-12-31 01:56:51 -05:00
|
|
|
|
2021-07-16 00:55:33 -04:00
|
|
|
type PartyProviderProps = {
|
|
|
|
session: Session;
|
|
|
|
children: React.ReactNode;
|
|
|
|
};
|
|
|
|
|
|
|
|
export function PartyProvider({ session, children }: PartyProviderProps) {
|
2021-07-17 19:12:09 -04:00
|
|
|
const [partyState, setPartyState] = useState<PartyState>({});
|
2020-12-31 01:56:51 -05:00
|
|
|
|
|
|
|
useEffect(() => {
|
2021-06-03 01:31:18 -04:00
|
|
|
function handleSocketPartyState(partyState: PartyState) {
|
2021-10-27 20:36:26 -04:00
|
|
|
if (partyState && session.id) {
|
2020-12-31 01:56:51 -05:00
|
|
|
const { [session.id]: _, ...otherMembersState } = partyState;
|
|
|
|
setPartyState(otherMembersState);
|
|
|
|
} else {
|
|
|
|
setPartyState({});
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-10-27 20:36:26 -04:00
|
|
|
session.socket?.on("party_state", handleSocketPartyState);
|
2020-12-31 01:56:51 -05:00
|
|
|
|
|
|
|
return () => {
|
2021-10-27 20:36:26 -04:00
|
|
|
session.socket?.off("party_state", handleSocketPartyState);
|
2020-12-31 01:56:51 -05:00
|
|
|
};
|
|
|
|
});
|
|
|
|
|
|
|
|
return (
|
|
|
|
<PartyContext.Provider value={partyState}>{children}</PartyContext.Provider>
|
|
|
|
);
|
|
|
|
}
|
|
|
|
|
2021-02-05 21:32:38 -05:00
|
|
|
export function useParty() {
|
|
|
|
const context = useContext(PartyContext);
|
|
|
|
if (context === undefined) {
|
|
|
|
throw new Error("useParty must be used within a PartyProvider");
|
|
|
|
}
|
|
|
|
return context;
|
|
|
|
}
|
|
|
|
|
2020-12-31 01:56:51 -05:00
|
|
|
export default PartyContext;
|