grungnet/src/contexts/PartyContext.js

39 lines
971 B
JavaScript
Raw Normal View History

import React, { useState, useEffect, useContext } from "react";
2020-12-31 01:56:51 -05:00
const PartyContext = React.createContext();
export function PartyProvider({ session, children }) {
const [partyState, setPartyState] = useState({});
useEffect(() => {
function handleSocketPartyState(partyState) {
if (partyState) {
const { [session.id]: _, ...otherMembersState } = partyState;
setPartyState(otherMembersState);
} else {
setPartyState({});
}
}
session.socket?.on("party_state", handleSocketPartyState);
2020-12-31 01:56:51 -05:00
return () => {
session.socket?.off("party_state", handleSocketPartyState);
2020-12-31 01:56:51 -05:00
};
});
return (
<PartyContext.Provider value={partyState}>{children}</PartyContext.Provider>
);
}
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;