Update Fix
This commit is contained in:
46
resources/js/admin/tailadmin/context/ThemeContext.tsx
Normal file
46
resources/js/admin/tailadmin/context/ThemeContext.tsx
Normal file
@@ -0,0 +1,46 @@
|
||||
import React, { createContext, useContext, useEffect, useMemo, useState } from "react";
|
||||
import type { ReactNode } from "react";
|
||||
|
||||
type Theme = "light" | "dark";
|
||||
|
||||
type ThemeContextType = {
|
||||
theme: Theme;
|
||||
setTheme: (theme: Theme) => void;
|
||||
toggleTheme: () => void;
|
||||
isInitialized: boolean;
|
||||
};
|
||||
|
||||
const ThemeContext = createContext<ThemeContextType | undefined>(undefined);
|
||||
|
||||
export function ThemeProvider({ children }: { children: ReactNode }) {
|
||||
const [theme, setThemeState] = useState<Theme>("light");
|
||||
const [isInitialized, setIsInitialized] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
const saved = localStorage.getItem("theme") as Theme | null;
|
||||
setThemeState(saved ?? "light");
|
||||
setIsInitialized(true);
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
if (!isInitialized) return;
|
||||
|
||||
localStorage.setItem("theme", theme);
|
||||
|
||||
if (theme === "dark") document.documentElement.classList.add("dark");
|
||||
else document.documentElement.classList.remove("dark");
|
||||
}, [theme, isInitialized]);
|
||||
|
||||
const setTheme = (t: Theme) => setThemeState(t);
|
||||
const toggleTheme = () => setThemeState((prev) => (prev === "dark" ? "light" : "dark"));
|
||||
|
||||
const value = useMemo(() => ({ theme, setTheme, toggleTheme, isInitialized }), [theme, isInitialized]);
|
||||
|
||||
return <ThemeContext.Provider value={value}>{children}</ThemeContext.Provider>;
|
||||
}
|
||||
|
||||
export function useTheme() {
|
||||
const ctx = useContext(ThemeContext);
|
||||
if (!ctx) throw new Error("useTheme must be used within a ThemeProvider");
|
||||
return ctx;
|
||||
}
|
||||
Reference in New Issue
Block a user