From 307c73591df349ef87e3b8b0cb392d81acfbc22b Mon Sep 17 00:00:00 2001 From: Imbus Date: Wed, 15 Nov 2023 11:17:00 +0100 Subject: [PATCH] Further polishing state management --- client-solid/src/GlobalState.tsx | 10 +++++++- client-solid/src/Navbar.tsx | 39 +++++++++++++------------------- 2 files changed, 25 insertions(+), 24 deletions(-) diff --git a/client-solid/src/GlobalState.tsx b/client-solid/src/GlobalState.tsx index 0929729..4cb3476 100644 --- a/client-solid/src/GlobalState.tsx +++ b/client-solid/src/GlobalState.tsx @@ -20,6 +20,7 @@ interface LoginContextType { username: Accessor; setUsername: (value: string) => void; loggedIn: () => boolean; + logOut: () => void; } // It is unclear to me if this is the idiomatic way to do this in Solid @@ -45,11 +46,18 @@ export function GlobalStateProvider(props: { return token() != "" && username() != ""; } + function logOut(): void { + localStorage.removeItem("token"); + localStorage.removeItem("username"); + setToken(""); + setUsername(""); + } + return ( <> {props.children} diff --git a/client-solid/src/Navbar.tsx b/client-solid/src/Navbar.tsx index 2803a87..fed39b0 100644 --- a/client-solid/src/Navbar.tsx +++ b/client-solid/src/Navbar.tsx @@ -17,41 +17,34 @@ function MenuItem(props: { href: string; children: JSXElement }): JSXElement { // Represents the menu bar at the top of the page function Menu(): JSXElement { - const login_ctx = useContext(LoginContext); + const login_ctx = useContext(LoginContext)!; return ( - + ); } export function Navbar(): JSXElement { - const modal_ctx = useContext(ModalContext); - const login_ctx = useContext(LoginContext); - - const logout = (): void => { - localStorage.removeItem("token"); - localStorage.removeItem("username"); - login_ctx?.setToken(""); - login_ctx?.setUsername(""); - }; + const modal_ctx = useContext(ModalContext)!; + const login_ctx = useContext(LoginContext)!; const clickHandler = (): void => { - if (login_ctx?.token() != "") logout(); - else modal_ctx?.setLoginModalOpen(true); + if (login_ctx.loggedIn()) login_ctx.logOut(); + else modal_ctx.setLoginModalOpen(true); }; return (