Skip to content

Commit

Permalink
feat: add dashboard context with localstorage support
Browse files Browse the repository at this point in the history
  • Loading branch information
rikhall1515 committed Apr 28, 2024
1 parent 973c207 commit 33ef4a3
Showing 1 changed file with 63 additions and 0 deletions.
63 changes: 63 additions & 0 deletions context/dashboard.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
"use client";

import {
type Dispatch,
type SetStateAction,
createContext,
useContext,
useEffect,
useState,
} from "react";

type DashboardStore = {
isExpanded: boolean;
setIsExpanded: Dispatch<SetStateAction<boolean>>;
toggle: () => void;
};

export const DashboardContext = createContext<DashboardStore | undefined>(
undefined
);
export function useDashboardContext() {
const sidebarStore = useContext(DashboardContext);

if (sidebarStore === undefined) {
throw new Error(
"useDashboardContext must be used with a DashboardContext provider"
);
}

return sidebarStore;
}

export default function DashboardContextProvider({
children,
}: {
children: React.ReactNode;
}) {
const [isExpanded, setIsExpanded] = useState(true);
useEffect(() => {
if (typeof window === "undefined") return;

setIsExpanded(
localStorage.getItem("preference_sidebar_expanded") === "true"
);
}, []);
const toggle = () => {
setIsExpanded(!isExpanded);
localStorage.setItem("preference_sidebar_expanded", `${!isExpanded}`);
};
return (
<>
<DashboardContext.Provider
value={{
isExpanded,
setIsExpanded,
toggle,
}}
>
{children}
</DashboardContext.Provider>
</>
);
}

0 comments on commit 33ef4a3

Please sign in to comment.