TwitchClone / src / utils / context / RoomDataContext.tsx
RoomDataContext.tsx
Raw
import { createContext, useContext, useState } from "react";
import { RoomDataSchema } from "../../types/roomData";
import { UserSchema } from "../../types/user";

type RoomDataContextType = {
  roomData: RoomDataSchema | null;
  setRoomData: React.Dispatch<React.SetStateAction<RoomDataSchema | null>>;
  userData: UserSchema | null;
  setUserData: React.Dispatch<React.SetStateAction<UserSchema | null>>;
};

const RoomDataContext = createContext<RoomDataContextType | undefined>(
  undefined
);

export const useRoomDataContext = () => {
  const context = useContext(RoomDataContext);
  if (!context) {
    throw new Error(
      "useRoomDataContext must be used within a RoomDataContextProvider"
    );
  }
  return context;
};

export const RoomDataContextProvider: React.FC<any> = ({ children }) => {
  const [roomData, setRoomData] = useState<RoomDataSchema | null>(null);
  const [userData, setUserData] = useState<UserSchema | null>(null);

  return (
    <RoomDataContext.Provider
      value={{ roomData, setRoomData, userData, setUserData }}
    >
      {children}
    </RoomDataContext.Provider>
  );
};