1 |
39d74503
|
Vaclav Honzik
|
import { createSlice } from '@reduxjs/toolkit'
|
2 |
37f6ff02
|
Vaclav Honzik
|
import { persistReducer } from 'redux-persist'
|
3 |
|
|
import storage from 'redux-persist/lib/storage'
|
4 |
8370b6c1
|
Vaclav Honzik
|
import { logIn } from './userThunks'
|
5 |
37f6ff02
|
Vaclav Honzik
|
|
6 |
|
|
export interface UserState {
|
7 |
|
|
accessToken?: string
|
8 |
|
|
refreshToken?: string
|
9 |
|
|
username: string
|
10 |
|
|
roles: string[]
|
11 |
|
|
isLoggedIn: boolean
|
12 |
8370b6c1
|
Vaclav Honzik
|
lastErr?: string // consumable for errors during thunks
|
13 |
37f6ff02
|
Vaclav Honzik
|
}
|
14 |
|
|
|
15 |
|
|
const persistConfig = {
|
16 |
|
|
key: 'auth',
|
17 |
|
|
storage, // localStorage for browsers
|
18 |
|
|
}
|
19 |
|
|
|
20 |
|
|
// Default state when user first starts the application
|
21 |
|
|
const initialState: UserState = {
|
22 |
|
|
roles: [],
|
23 |
|
|
isLoggedIn: false,
|
24 |
|
|
username: '',
|
25 |
|
|
}
|
26 |
|
|
|
27 |
|
|
export const userSlice = createSlice({
|
28 |
|
|
name: 'user', // name to generate action types
|
29 |
|
|
|
30 |
|
|
initialState, // default state
|
31 |
|
|
|
32 |
|
|
// Reducers that update the state
|
33 |
|
|
reducers: {
|
34 |
8370b6c1
|
Vaclav Honzik
|
logout: () => initialState, // Reset to the inital state
|
35 |
|
|
refreshTokens: (state, action) => ({
|
36 |
|
|
...state,
|
37 |
|
|
accessToken: action.payload.accessToken,
|
38 |
|
|
refreshToken: action.payload.refreshToken,
|
39 |
|
|
}),
|
40 |
|
|
setErr: (state, action) => ({
|
41 |
|
|
...state,
|
42 |
|
|
lastErr: action.payload,
|
43 |
|
|
}),
|
44 |
fc79a8cb
|
Vaclav Honzik
|
setUserState: (state, action) => {
|
45 |
|
|
return ({ ...state, ...action.payload })
|
46 |
|
|
},
|
47 |
37f6ff02
|
Vaclav Honzik
|
},
|
48 |
|
|
|
49 |
8370b6c1
|
Vaclav Honzik
|
// Thunks
|
50 |
|
|
extraReducers: (builder) => {
|
51 |
fc79a8cb
|
Vaclav Honzik
|
builder.addCase(logIn.fulfilled, (state, action) => {
|
52 |
|
|
return ({ ...state, ...action.payload })
|
53 |
|
|
})
|
54 |
|
|
builder.addCase(logIn.rejected, (state, action) => {
|
55 |
|
|
if (action.payload && typeof action.payload === 'string') {
|
56 |
|
|
return ({ ...state, lastErr: action.payload })
|
57 |
|
|
}
|
58 |
|
|
})
|
59 |
8370b6c1
|
Vaclav Honzik
|
},
|
60 |
37f6ff02
|
Vaclav Honzik
|
})
|
61 |
|
|
|
62 |
39d74503
|
Vaclav Honzik
|
|
63 |
37f6ff02
|
Vaclav Honzik
|
const userReducer = persistReducer(persistConfig, userSlice.reducer)
|
64 |
8370b6c1
|
Vaclav Honzik
|
|
65 |
fc79a8cb
|
Vaclav Honzik
|
export const { logout, refreshTokens, setErr, setUserState } = userSlice.actions
|
66 |
|
|
|
67 |
37f6ff02
|
Vaclav Honzik
|
export default userReducer
|