- Implement CameraFeed context and provider with reducer for state management
- able to switch footage on tab clicks
This commit is contained in:
16
src/app/context/CameraFeedContext.ts
Normal file
16
src/app/context/CameraFeedContext.ts
Normal file
@@ -0,0 +1,16 @@
|
||||
import { createContext, useContext } from "react";
|
||||
import type { CameraFeedAction, CameraFeedState } from "../../types/types";
|
||||
|
||||
type CameraFeedContextType = {
|
||||
state: CameraFeedState;
|
||||
// check and refactor
|
||||
dispatch: (state: CameraFeedAction) => void;
|
||||
};
|
||||
|
||||
export const CameraFeedContext = createContext<CameraFeedContextType | null>(null);
|
||||
|
||||
export const useCameraFeedContext = () => {
|
||||
const ctx = useContext(CameraFeedContext);
|
||||
if (!ctx) throw new Error("useCameraFeedContext must be used inside <CameraFeedContext.Provider>");
|
||||
return ctx;
|
||||
};
|
||||
@@ -1,11 +1,14 @@
|
||||
import type { PropsWithChildren } from "react";
|
||||
import { QueryProvider } from "./QueryProviders";
|
||||
import { WebSocketProvider } from "./WebSocketProvider";
|
||||
import { CameraFeedProvider } from "./CameraFeedProvider";
|
||||
|
||||
export const AppProviders = ({ children }: PropsWithChildren) => {
|
||||
return (
|
||||
<QueryProvider>
|
||||
<WebSocketProvider>{children}</WebSocketProvider>
|
||||
<CameraFeedProvider>
|
||||
<WebSocketProvider>{children}</WebSocketProvider>
|
||||
</CameraFeedProvider>
|
||||
</QueryProvider>
|
||||
);
|
||||
};
|
||||
|
||||
9
src/app/providers/CameraFeedProvider.tsx
Normal file
9
src/app/providers/CameraFeedProvider.tsx
Normal file
@@ -0,0 +1,9 @@
|
||||
import { useReducer, type ReactNode } from "react";
|
||||
import { CameraFeedContext } from "../context/CameraFeedContext";
|
||||
import { initialState, reducer } from "../reducers/cameraFeedReducer";
|
||||
|
||||
export const CameraFeedProvider = ({ children }: { children: ReactNode }) => {
|
||||
const [state, dispatch] = useReducer(reducer, initialState);
|
||||
|
||||
return <CameraFeedContext.Provider value={{ state, dispatch }}>{children}</CameraFeedContext.Provider>;
|
||||
};
|
||||
17
src/app/reducers/cameraFeedReducer.ts
Normal file
17
src/app/reducers/cameraFeedReducer.ts
Normal file
@@ -0,0 +1,17 @@
|
||||
import type { CameraFeedAction, CameraFeedState } from "../../types/types";
|
||||
|
||||
export const initialState: CameraFeedState = {
|
||||
cameraFeedID: "A",
|
||||
};
|
||||
|
||||
export function reducer(state: CameraFeedState, action: CameraFeedAction) {
|
||||
switch (action.type) {
|
||||
case "SET_CAMERA_FEED":
|
||||
return {
|
||||
...state,
|
||||
cameraFeedID: action.payload,
|
||||
};
|
||||
default:
|
||||
return state;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user