Restructure

This commit is contained in:
Imbus 2023-11-22 15:29:27 +01:00
parent da48f005a3
commit 22a3ca1769
16 changed files with 44 additions and 34 deletions

View file

@ -0,0 +1,85 @@
import {
Accessor,
JSXElement,
createContext,
createSignal,
onMount,
} from "solid-js";
// Representing the state of varoious modals.
// So far we only have one modal, but we can add more later
// by adding more fields to this interface, or maybe an enum
interface ModalContextType {
isOpen: Accessor<boolean>;
setOpen: (value: boolean) => void;
}
interface LoginContextType {
token: Accessor<string>;
setToken: (value: string) => void;
username: Accessor<string>;
setUsername: (value: string) => void;
loggedIn: () => boolean;
logOut: () => void;
logIn: (username: string, token: string) => void;
}
// It is unclear to me if this is the idiomatic way to do this in Solid
export const ModalContext = createContext<ModalContextType>();
export const LoginContext = createContext<LoginContextType>();
export function GlobalStateProvider(props: {
children: JSXElement;
}): JSXElement {
// All of these are passed into context providers
const [loginModalOpen, setLoginModalOpen] = createSignal(false);
const [token, setToken] = createSignal("");
const [username, setUsername] = createSignal("");
onMount(() => {
// This may not be the best place to do this.
localStorage.getItem("token") && setToken(localStorage.getItem("token")!);
localStorage.getItem("username") &&
setUsername(localStorage.getItem("username")!);
});
function loggedIn(): boolean {
return token() != "" && username() != "";
}
function logIn(username: string, token: string): void {
setUsername(username);
setToken(token);
localStorage.setItem("token", token);
localStorage.setItem("username", username);
}
function logOut(): void {
localStorage.removeItem("token");
localStorage.removeItem("username");
setToken("");
setUsername("");
}
return (
<>
<ModalContext.Provider
value={{ isOpen: loginModalOpen, setOpen: setLoginModalOpen }}
>
<LoginContext.Provider
value={{
token,
setToken,
username,
setUsername,
loggedIn,
logOut,
logIn,
}}
>
{props.children}
</LoginContext.Provider>
</ModalContext.Provider>
</>
);
}