Spaces:
Sleeping
Sleeping
File size: 1,324 Bytes
345b8ff |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 |
"use client";
import { createContext, useContext, useState, useEffect, ReactNode } from "react";
import { DEFAULT_TENANT_ID, TENANT_STORAGE_KEY } from "@/lib/constants";
type TenantContextType = {
tenantId: string;
setTenantId: (id: string) => void;
isLoading: boolean;
};
const TenantContext = createContext<TenantContextType | undefined>(undefined);
export function TenantProvider({ children }: { children: ReactNode }) {
const [tenantId, setTenantIdState] = useState("");
const [isLoading, setIsLoading] = useState(true);
// Load from localStorage on mount
useEffect(() => {
const saved = localStorage.getItem(TENANT_STORAGE_KEY);
setTenantIdState(saved || DEFAULT_TENANT_ID);
setIsLoading(false);
}, []);
const setTenantId = (id: string) => {
const trimmed = id.trim();
setTenantIdState(trimmed);
if (trimmed) {
localStorage.setItem(TENANT_STORAGE_KEY, trimmed);
} else {
localStorage.removeItem(TENANT_STORAGE_KEY);
}
};
return (
<TenantContext.Provider value={{ tenantId, setTenantId, isLoading }}>
{children}
</TenantContext.Provider>
);
}
export function useTenant() {
const context = useContext(TenantContext);
if (!context) {
throw new Error("useTenant must be used within TenantProvider");
}
return context;
}
|