-
Notifications
You must be signed in to change notification settings - Fork 0
/
useAuth.ts
81 lines (70 loc) · 2.12 KB
/
useAuth.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
import { useMemo } from 'react';
import { useNavigate } from 'react-router-dom';
import { useAppSelector, useAppDispatch } from './selector-dispatch-hooks';
import {
selectCurrentUser,
setAuthenticatedState,
removeAuthenticatedState,
} from '../../features/auth/authSlice';
import {
useLoginMutation,
useLogoutMutation,
useRefreshAccessTokenMutation,
} from '../../app/apiSlice';
import type { LoginFields } from '../../app/types';
import getErrorMessage, { toErrorWithMessage } from '../utils/getErrorMessage';
const useAuth = () => {
const user = useAppSelector(selectCurrentUser);
const dispatch = useAppDispatch();
const navigate = useNavigate();
const [loginMutation] = useLoginMutation();
const [logoutMutation] = useLogoutMutation();
const [
refreshAccessTokenMutation,
] = useRefreshAccessTokenMutation();
const login = async (loginFields: LoginFields) => {
try {
const data = await loginMutation(loginFields).unwrap();
if (data.accessToken && data.username) {
const loginResponseData = {
username: data.username,
accessToken: data.accessToken,
};
dispatch(setAuthenticatedState(loginResponseData));
} else {
throw new Error('Something went wrong. Try again.');
}
} catch (error) {
throw toErrorWithMessage(error) as Error;
}
};
const refreshAccessToken = async () => {
try {
const data = await refreshAccessTokenMutation().unwrap();
if (data.accessToken && data.username) {
const refreshResponseData = {
username: data.username,
accessToken: data.accessToken,
};
dispatch(setAuthenticatedState(refreshResponseData));
}
} catch (error) {
console.error(getErrorMessage(error));
}
};
const logout = async () => {
try {
await logoutMutation().unwrap();
} catch (error) {
console.error(getErrorMessage(error));
}
dispatch(removeAuthenticatedState());
navigate('/login');
};
return [useMemo(() => (user), [user]), {
login,
logout,
refreshAccessToken,
}] as const;
};
export default useAuth;