mirror of
https://github.com/apricote/Listory.git
synced 2026-01-13 21:21:02 +00:00
feat(frontend): redo setup with ts+tailwind and implement auth+header
This commit is contained in:
parent
f2065d3f1f
commit
05f230a7ce
32 changed files with 5927 additions and 2749 deletions
53
frontend/src/hooks/use-auth.tsx
Normal file
53
frontend/src/hooks/use-auth.tsx
Normal file
|
|
@ -0,0 +1,53 @@
|
|||
import React, { createContext, useContext, useEffect, useState } from "react";
|
||||
import { getUsersMe, UnauthenticatedError } from "../api/api";
|
||||
import { User } from "../api/user";
|
||||
|
||||
const authContext = createContext<AuthContext>(
|
||||
(undefined as any) as AuthContext
|
||||
);
|
||||
|
||||
// Provider component that wraps your app and makes auth object ...
|
||||
// ... available to any child component that calls useAuth().
|
||||
|
||||
interface AuthContext {
|
||||
user: { id: string; displayName: string } | null;
|
||||
isLoaded: boolean;
|
||||
loginWithSpotifyProps: () => { href: string };
|
||||
}
|
||||
|
||||
export const ProvideAuth: React.FC = ({ children }) => {
|
||||
const auth = useProvideAuth();
|
||||
|
||||
return <authContext.Provider value={auth}>{children}</authContext.Provider>;
|
||||
};
|
||||
|
||||
export function useAuth() {
|
||||
return useContext(authContext);
|
||||
}
|
||||
|
||||
function useProvideAuth(): AuthContext {
|
||||
const [isLoaded, setIsLoaded] = useState(false);
|
||||
const [user, setUser] = useState<User | null>(null);
|
||||
|
||||
const loginWithSpotifyProps = () => ({ href: "/api/v1/auth/spotify" });
|
||||
|
||||
useEffect(() => {
|
||||
(async () => {
|
||||
try {
|
||||
console.log("before calling getUsersMe");
|
||||
const currentUser = await getUsersMe();
|
||||
setUser(currentUser);
|
||||
} catch (err) {
|
||||
if (err instanceof UnauthenticatedError) {
|
||||
// User is not logged in
|
||||
} else {
|
||||
console.error("Error while checking login state:", err);
|
||||
}
|
||||
} finally {
|
||||
setIsLoaded(true);
|
||||
}
|
||||
})();
|
||||
}, []);
|
||||
|
||||
return { isLoaded, user, loginWithSpotifyProps };
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue