fiddy/apps/web/features/auth/hooks/use-auth.ts

73 lines
2.2 KiB
TypeScript

import { useCallback, useState } from "react";
import { authLogin, authMe, authRegister, authLogout } from "@/lib/client/auth";
import type { User } from "@/lib/shared/types";
import type { ApiResult } from "@/lib/client/fetch-json";
type LoginInput = {
email: string;
password: string;
remember: boolean;
};
type RegisterInput = {
email: string;
password: string;
displayName?: string;
};
export default function useAuth() {
const [error, setError] = useState("");
const [loading, setLoading] = useState(false);
function isError<T>(result: ApiResult<T>): result is { error: { code: string; message: string } } {
return "error" in result;
}
const checkSession = useCallback(async () => {
const res = await authMe();
if (isError(res)) return null;
return res.data.user as User;
}, []);
const login = useCallback(async (input: LoginInput) => {
setError("");
setLoading(true);
try {
const result = await authLogin(input);
if (isError(result)) {
setError(result.error.message || "");
return { ok: false, error: result.error.message || "" };
}
return { ok: true } as { ok: true };
} finally {
setLoading(false);
}
}, []);
const register = useCallback(async (input: RegisterInput) => {
setError("");
setLoading(true);
try {
const result = await authRegister(input);
if (isError(result)) {
setError(result.error.message || "");
return { ok: false, error: result.error.message || "" };
}
return { ok: true } as { ok: true };
} finally {
setLoading(false);
}
}, []);
const logout = useCallback(async () => {
const result = await authLogout();
if (isError(result)) {
setError(result.error.message || "");
return { ok: false, error: result.error.message || "" };
}
return { ok: true } as { ok: true };
}, []);
return { checkSession, login, register, logout, error, loading };
}