Initial React project
This commit is contained in:
47
src/presentation/auth/hooks/useAuthViewModel.ts
Normal file
47
src/presentation/auth/hooks/useAuthViewModel.ts
Normal file
@@ -0,0 +1,47 @@
|
||||
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,
|
||||
};
|
||||
}
|
||||
Reference in New Issue
Block a user