Files
dh-inspeccion-v2/web-v2/src/context/OperationalContext.tsx
T

65 lines
2.1 KiB
TypeScript

import { createContext, useContext, useEffect, useMemo, useState } from 'react';
import type { PropsWithChildren } from 'react';
interface OperationalContextValue {
areaId: string;
companyId: string;
setAreaId: (areaId: string) => void;
setCompanyId: (companyId: string) => void;
setContext: (areaId: string, companyId?: string) => void;
clearContext: () => void;
}
const STORAGE_KEY = 'dhv2.operational-context';
const OperationalContext = createContext<OperationalContextValue | null>(null);
function readStoredContext(): { areaId: string; companyId: string } {
try {
const raw = window.localStorage.getItem(STORAGE_KEY);
if (!raw) return { areaId: '', companyId: '' };
const parsed = JSON.parse(raw) as { areaId?: unknown; companyId?: unknown };
return {
areaId: typeof parsed.areaId === 'string' ? parsed.areaId : '',
companyId: typeof parsed.companyId === 'string' ? parsed.companyId : '',
};
} catch {
return { areaId: '', companyId: '' };
}
}
export function OperationalContextProvider({ children }: PropsWithChildren) {
const initial = useMemo(readStoredContext, []);
const [areaId, setAreaState] = useState(initial.areaId);
const [companyId, setCompanyState] = useState(initial.companyId);
useEffect(() => {
window.localStorage.setItem(STORAGE_KEY, JSON.stringify({ areaId, companyId }));
}, [areaId, companyId]);
const value = useMemo<OperationalContextValue>(() => ({
areaId,
companyId,
setAreaId: (nextAreaId) => {
setAreaState(nextAreaId);
setCompanyState('');
},
setCompanyId: setCompanyState,
setContext: (nextAreaId, nextCompanyId = '') => {
setAreaState(nextAreaId);
setCompanyState(nextAreaId ? nextCompanyId : '');
},
clearContext: () => {
setAreaState('');
setCompanyState('');
},
}), [areaId, companyId]);
return <OperationalContext.Provider value={value}>{children}</OperationalContext.Provider>;
}
export function useOperationalContext() {
const value = useContext(OperationalContext);
if (!value) throw new Error('useOperationalContext debe usarse dentro de OperationalContextProvider');
return value;
}