-
Notifications
You must be signed in to change notification settings - Fork 288
Expand file tree
/
Copy pathreducer.tsx
More file actions
60 lines (58 loc) · 1.45 KB
/
reducer.tsx
File metadata and controls
60 lines (58 loc) · 1.45 KB
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
import { User } from '@auth0/auth0-spa-js';
import { AuthState } from './auth-state';
import { isEqual } from 'lodash-es';
type Action =
| { type: 'LOGIN_POPUP_STARTED' }
| {
type:
| 'INITIALISED'
| 'LOGIN_POPUP_COMPLETE'
| 'GET_ACCESS_TOKEN_COMPLETE'
| 'HANDLE_REDIRECT_COMPLETE';
user: User | undefined;
}
| { type: 'LOGOUT' }
| { type: 'ERROR'; error: Error };
/**
* Handles how that state changes in the `useAuth0` hook.
*/
export const reducer = <TUser extends User = User>(state: AuthState<TUser>, action: Action): AuthState<TUser> => {
switch (action.type) {
case 'LOGIN_POPUP_STARTED':
return {
...state,
isLoading: true,
};
case 'LOGIN_POPUP_COMPLETE':
case 'INITIALISED':
return {
...state,
isAuthenticated: !!action.user,
user: action.user as TUser | undefined,
isLoading: false,
error: undefined,
};
case 'HANDLE_REDIRECT_COMPLETE':
case 'GET_ACCESS_TOKEN_COMPLETE':
if (isEqual(state.user, action.user)) {
return state;
}
return {
...state,
isAuthenticated: !!action.user,
user: action.user as TUser | undefined,
};
case 'LOGOUT':
return {
...state,
isAuthenticated: false,
user: undefined,
};
case 'ERROR':
return {
...state,
isLoading: false,
error: action.error,
};
}
};