48 lines
1.3 KiB
TypeScript
48 lines
1.3 KiB
TypeScript
import { useMemo, useState } from 'react';
|
|
import { AuthViewModel, type AuthActionResult, type RegisterInput } from '../../../mvvm/viewmodels/AuthViewModel';
|
|
|
|
export function useAuthViewModel() {
|
|
const viewModel = useMemo(() => new AuthViewModel(), []);
|
|
const [isLoading, setIsLoading] = useState(false);
|
|
const [result, setResult] = useState<AuthActionResult | null>(null);
|
|
|
|
async function runAction(action: () => Promise<AuthActionResult>) {
|
|
setIsLoading(true);
|
|
setResult(null);
|
|
try {
|
|
const next = await action();
|
|
setResult(next);
|
|
return next;
|
|
} catch (error) {
|
|
const failed: AuthActionResult = {
|
|
ok: false,
|
|
message: error instanceof Error ? error.message : 'Noget gik galt.',
|
|
};
|
|
setResult(failed);
|
|
return failed;
|
|
} finally {
|
|
setIsLoading(false);
|
|
}
|
|
}
|
|
|
|
function login(email: string, password: string, rememberMe: boolean) {
|
|
return runAction(() => viewModel.login(email, password, rememberMe));
|
|
}
|
|
|
|
function register(input: RegisterInput) {
|
|
return runAction(() => viewModel.register(input));
|
|
}
|
|
|
|
function forgotPassword(email: string) {
|
|
return runAction(() => viewModel.forgotPassword(email));
|
|
}
|
|
|
|
return {
|
|
isLoading,
|
|
result,
|
|
login,
|
|
register,
|
|
forgotPassword,
|
|
};
|
|
}
|