add context

This commit is contained in:
2026-06-07 23:07:59 +02:00
parent 82c24ba9d4
commit ba05fbedd3
3 changed files with 70 additions and 18 deletions
+47
View File
@@ -0,0 +1,47 @@
import {
createContext,
type Dispatch,
type ReactNode,
type SetStateAction,
useContext,
useState,
} from "react";
interface ILichessUser {
username: string;
isLoggedIn: boolean;
}
interface ILichessUserContextType {
user: ILichessUser | null;
setUser: Dispatch<SetStateAction<ILichessUser | null>>;
logout: () => void;
}
const LichessUserContext = createContext<ILichessUserContextType | undefined>(
undefined,
);
export const LichessUserProvider = ({ children }: { children: ReactNode }) => {
const [user, setUser] = useState<ILichessUser | null>(null);
const logout = () => {
setUser(null);
};
// TODO useEffect to check and login user on mount
return (
<LichessUserContext.Provider value={{ user, setUser, logout }}>
{children}
</LichessUserContext.Provider>
);
};
export const useLichessUser = () => {
const context = useContext(LichessUserContext);
if (!context) {
throw new Error("useLichessUser must be used within a LichessUserProvider");
}
return context;
};
+5 -3
View File
@@ -1,14 +1,14 @@
import { useServerFn } from "@tanstack/react-start";
import { useState } from "react";
import { useLichessUser } from "#/context/LichessUserContext.tsx";
import { getToken, login } from "#/server/lichess.ts";
export const useLichess = () => {
const [lichessUser, setLichessUser] = useState();
const { user, setUser, logout } = useLichessUser();
const triggerLogin = useServerFn(login);
const trigggerGetToken = useServerFn(getToken);
console.log("Lichess User:", lichessUser);
console.log("Lichess User:", user);
const lichessTokenVerification = async ({ code }) => {
await trigggerGetToken();
@@ -21,6 +21,8 @@ export const useLichess = () => {
const lichessLogout = () => {
console.log("Lichess Logout");
// TODO remove cookies
logout();
};
return {
+3
View File
@@ -4,6 +4,7 @@ import { TanStackRouterDevtoolsPanel } from "@tanstack/react-router-devtools";
import { type ReactNode, Suspense } from "react";
import { ToastContainer } from "react-toastify";
import { MatomoAnalytics } from "#/components/MatomoAnalytics.tsx";
import { LichessUserProvider } from "#/context/LichessUserContext.tsx";
import Footer from "../components/Footer";
import Header from "../components/Header";
import appCss from "../styles.css?url";
@@ -51,6 +52,7 @@ function RootDocument({ children }: { children: ReactNode }) {
<HeadContent />
</head>
<body className="font-sans antialiased">
<LichessUserProvider>
<Header />
{children}
<ToastContainer position="bottom-right" />
@@ -66,6 +68,7 @@ function RootDocument({ children }: { children: ReactNode }) {
},
]}
/>
</LichessUserProvider>
<Scripts />
<Suspense fallback={null}>
<MatomoAnalytics />