You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
Application-Web/src/pages/template/Header.tsx

74 lines
2.4 KiB

import AccountSvg from "../../assets/account.svg?react"
import "../../style/template/header.css"
import { startTransition, useEffect, useState } from "react"
import { fetchAPIGet } from "../../Fetcher.ts"
import { getSession, saveSession } from "../../api/session.ts"
import { useNavigate } from "react-router-dom"
export function Header() {
const session = getSession()
const [username, setUsername] = useState<string | null>(
session.username ?? null,
)
const navigate = useNavigate()
useEffect(() => {
async function loadUsername() {
const response = await fetchAPIGet("user", false)
if (response.status == 401) {
//if unauthorized
return
}
//TODO check if the response is ok and handle errors
const { name: username } = await response.json()
saveSession({ ...session, username })
setUsername(username)
}
// if the user is authenticated and the username is not already present in the session,
if (session.auth && !session.username) loadUsername()
}, [session])
return (
<div id="header">
<div id="header-left"></div>
<div id="header-center">
<p
id="iqball"
className="clickable"
onClick={() => startTransition(() => navigate("/"))}>
IQBall
</p>
</div>
<div id="header-right">
<div
className="clickable"
id="clickable-header-right"
onClick={() => {
if (username) {
startTransition(() => {
navigate("/settings")
})
return
}
saveSession({
...session,
urlTarget: location.pathname,
})
startTransition(() => {
navigate("/login")
})
}}>
{/* <AccountSvg id="img-account" /> */}
<AccountSvg id="img-account" />
<p id="username">{username ?? "Log In"}</p>
</div>
</div>
</div>
)
}