30 lines
809 B
TypeScript
30 lines
809 B
TypeScript
import { createContext, useContext } from "react";
|
|
import { useCurrentUser } from "../api";
|
|
import type { UserLogged } from "../resources/users";
|
|
|
|
export type Auth = {
|
|
loggedUser: UserLogged | null;
|
|
isLoading: boolean;
|
|
};
|
|
|
|
const AuthContext = createContext<Auth | undefined>(undefined);
|
|
|
|
export function AuthProvider({ children }: { children: React.ReactNode }) {
|
|
const { data: loggedUser, isLoading } = useCurrentUser();
|
|
|
|
const value: Auth = {
|
|
loggedUser: loggedUser ?? null,
|
|
isLoading,
|
|
};
|
|
|
|
return <AuthContext.Provider value={value}>{children}</AuthContext.Provider>;
|
|
}
|
|
|
|
export function useAuth(): Auth {
|
|
const context = useContext(AuthContext);
|
|
if (!context) {
|
|
throw new Error("useAuth must be used inside AuthProvider");
|
|
}
|
|
return context;
|
|
}
|