-
Notifications
You must be signed in to change notification settings - Fork 1
/
authSlice.ts
71 lines (65 loc) · 2.18 KB
/
authSlice.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
import { createSlice, PayloadAction } from '@reduxjs/toolkit';
import { loginApi } from '../api/loginApi';
import { registerApi } from '../api/registerApi';
import { userApi } from '@/features/users/';
import { AuthState, User } from '../types/auth';
import type { RootState } from '@/stores/store';
import storage from '@/utils/storage';
const initialState: AuthState = {
user: null,
token: null,
remember: null,
};
const prepareUser = (user: User): User => {
return {
...user,
image: user.image || `https://image.dummyjson.com/300x300/008080/ffffff?text=${user.username}`,
};
};
const slice = createSlice({
name: 'auth',
initialState,
reducers: {
logout: (state) => {
state.user = null;
state.token = null;
state.remember = null;
storage.clearToken();
},
rememberAuth: (state, { payload }: PayloadAction<boolean>) => {
state.remember = payload;
},
},
extraReducers: (builder) => {
builder
.addMatcher(loginApi.endpoints.login.matchFulfilled, (state, { payload }) => {
const { token, ...user } = payload;
state.token = token;
state.user = prepareUser(user);
if (state.remember) {
storage.setToken(token);
}
})
.addMatcher(loginApi.endpoints.loginToken.matchFulfilled, (state, { payload }) => {
const { token, ...user } = payload;
state.token = token;
state.user = prepareUser(user);
if (state.remember) {
storage.setToken(token);
}
})
.addMatcher(loginApi.endpoints.loginToken.matchRejected, () => {
storage.clearToken();
})
.addMatcher(registerApi.endpoints.register.matchFulfilled, () => {
// TODO: Use a backend that supports login on registration by returning token, instead of logging in manually in the component
})
.addMatcher(userApi.endpoints.getAuthUserById.matchFulfilled, (state, { payload }) => {
const { password: _, ...user } = payload;
state.user = prepareUser(user);
});
},
});
export const { logout, rememberAuth } = slice.actions;
export default slice.reducer;
export const selectCurrentUser = (state: RootState) => state.auth.user;