Skip to content

Commit

Permalink
feat: add loading state on auth
Browse files Browse the repository at this point in the history
  • Loading branch information
2wheeh committed Mar 12, 2024
1 parent 2c134e4 commit f20a6e7
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 21 deletions.
40 changes: 20 additions & 20 deletions ui/src/components/auth/client/sign-button.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,28 +4,28 @@ import Text from '@/components/common/server/text';
import { useAuth } from '@/context/auth/auth-context';

export default function SignButton() {
const { user, signOut, signIn } = useAuth();
const { user, signOut, signIn, loading } = useAuth();

if (user) {
return (
<button
// eslint-disable-next-line @typescript-eslint/no-misused-promises
onClick={async () => {
await signOut();
}}
>
<Text size="lg" weight="medium">
Sign Out
</Text>
</button>
);
}
const state = loading ? 'loading' : user ? 'signed-in' : 'signed-out';

return (
<button onClick={() => signIn()}>
<Text size="lg" weight="medium">
Sign In
</Text>
</button>
// TODO: better UI for loading state
<div className="w-20">
{state === 'loading' && null}
{state === 'signed-in' && (
<button onClick={() => void signOut()}>
<Text size="lg" weight="medium">
Sign Out
</Text>
</button>
)}
{state === 'signed-out' && (
<button onClick={() => signIn()}>
<Text size="lg" weight="medium">
Sign In
</Text>
</button>
)}
</div>
);
}
12 changes: 11 additions & 1 deletion ui/src/context/auth/auth-context.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,15 +11,19 @@ interface ContextShape {
user?: User;
signOut: () => Promise<void>;
signIn: () => void;
loading: boolean;
}

const AuthContext = createContext<ContextShape | null>(null);

export function AuthProvider({ children }: { children: ReactNode }) {
const [user, setUser] = useState<User>();
const [loading, setLoading] = useState(true);

const handleGetUserSelf = async () => {
setLoading(true);
const user = await getUserSelf();
setLoading(false);
setUser(user);
};

Expand All @@ -39,7 +43,9 @@ export function AuthProvider({ children }: { children: ReactNode }) {
const pathname = usePathname();
useEffect(() => {
const protect = async () => {
setLoading(true);
const isLoggedIn = !!(await getUserSelf());
setLoading(false);
if (!isLoggedIn) {
// TODO: redirect to the sign-in page
signIn();
Expand All @@ -51,7 +57,11 @@ export function AuthProvider({ children }: { children: ReactNode }) {
}
}, [pathname, user]);

return <AuthContext.Provider value={{ user, signOut, signIn }}>{children}</AuthContext.Provider>;
return (
<AuthContext.Provider value={{ user, signOut, signIn, loading }}>
{children}
</AuthContext.Provider>
);
}

export function useAuth() {
Expand Down

0 comments on commit f20a6e7

Please sign in to comment.