tahamajs/IE / Projects /front /src /context /FeatureFlagContext.tsx
tahamajs's picture
download
raw
4.47 kB
// src/context/FeatureFlagContext.tsx - Full fix
import { createContext, useContext, useEffect, useState, useCallback, ReactNode } from "react";
import { useAuth } from "./AuthContext";
import api from "@/lib/api";
interface FeatureFlags {
enableAiAssistant: boolean;
enableVideoCalls: boolean;
enableOfflineMode: boolean;
enableAnalytics: boolean;
enablePWA: boolean;
enableCollaboration: boolean;
enableAdvancedSearch: boolean;
enableOpenAccess: boolean;
enablePeerReview: boolean;
enableGrants: boolean;
[key: string]: boolean;
}
interface FeatureFlagContextValue {
flags: FeatureFlags;
isEnabled: (flag: keyof FeatureFlags) => boolean;
refreshFlags: () => Promise<void>;
setFlag: (flag: keyof FeatureFlags, value: boolean) => void;
isLoading: boolean;
}
const DEFAULT_FLAGS: FeatureFlags = {
enableAiAssistant: true,
enableVideoCalls: false,
enableOfflineMode: true,
enableAnalytics: true,
enablePWA: false,
enableCollaboration: true,
enableAdvancedSearch: true,
enableOpenAccess: true,
enablePeerReview: true,
enableGrants: true,
};
const STORAGE_KEY = "feature_flags";
const FeatureFlagContext = createContext<FeatureFlagContextValue | null>(null);
export function FeatureFlagProvider({ children }: { children: ReactNode }) {
const { user } = useAuth();
const [flags, setFlags] = useState<FeatureFlags>(() => {
try {
const stored = localStorage.getItem(STORAGE_KEY);
if (stored) {
const parsed = JSON.parse(stored);
return { ...DEFAULT_FLAGS, ...parsed };
}
} catch (err) {
console.error("Failed to load feature flags from localStorage:", err);
}
return DEFAULT_FLAGS;
});
const [isLoading, setIsLoading] = useState(false);
useEffect(() => {
try {
localStorage.setItem(STORAGE_KEY, JSON.stringify(flags));
} catch (err) {
console.error("Failed to save feature flags to localStorage:", err);
}
}, [flags]);
const refreshFlags = useCallback(async () => {
if (!user) return;
setIsLoading(true);
try {
// ✅ Use a try-catch with specific error handling
const response = await api.get("/feature-flags", {
// ✅ Add a timeout to prevent hanging
timeout: 5000,
});
const remoteFlags = response.data;
setFlags(prev => ({ ...prev, ...remoteFlags }));
} catch (err: any) {
// ✅ Check for 404 specifically
if (err.response?.status === 404) {
console.info("ℹ️ Feature flags endpoint not available (404), using local flags");
} else if (err.code === "ECONNREFUSED" || err.code === "ERR_NETWORK") {
console.info("ℹ️ Backend unavailable, using cached feature flags");
} else if (err.code === "ERR_CANCELED" || err.message?.includes("canceled")) {
console.info("ℹ️ Request was canceled, using local flags");
} else {
console.warn("Failed to fetch feature flags from backend:", err.message);
}
// ✅ Don't throw - just use local flags
} finally {
setIsLoading(false);
}
}, [user]);
useEffect(() => {
if (user) {
refreshFlags();
} else {
try {
const stored = localStorage.getItem(STORAGE_KEY);
if (stored) {
const parsed = JSON.parse(stored);
setFlags(prev => ({ ...DEFAULT_FLAGS, ...parsed }));
} else {
setFlags(DEFAULT_FLAGS);
}
} catch {
setFlags(DEFAULT_FLAGS);
}
}
}, [user, refreshFlags]);
const isEnabled = useCallback((flag: keyof FeatureFlags): boolean => {
return flags[flag] ?? false;
}, [flags]);
const setFlag = useCallback((flag: keyof FeatureFlags, value: boolean) => {
const previousValue = flags[flag];
setFlags(prev => ({ ...prev, [flag]: value }));
// ✅ Attempt to sync to backend, but don't fail if it's not available
api.post("/feature-flags", { flag, value }).catch(() => {
setFlags(prev => ({ ...prev, [flag]: previousValue }));
});
}, [flags]);
const value: FeatureFlagContextValue = {
flags,
isEnabled,
refreshFlags,
setFlag,
isLoading,
};
return (
<FeatureFlagContext.Provider value={value}>
{children}
</FeatureFlagContext.Provider>
);
}
export const useFeatureFlags = () => {
const ctx = useContext(FeatureFlagContext);
if (!ctx) throw new Error("useFeatureFlags must be used within FeatureFlagProvider");
return ctx;
};

Xet Storage Details

Size:
4.47 kB
·
Xet hash:
280550c082d6d5d5340ab147b15b0d8586e0af3e86f7474f64abe7cab353aac2

Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.