1
|
import { createSlice } from "@reduxjs/toolkit"
|
2
|
import { checkAuth, login, logout } from "../actions/userThunks"
|
3
|
|
4
|
export interface UserState {
|
5
|
username: string
|
6
|
loggedIn: boolean
|
7
|
role: string
|
8
|
lastError?: string
|
9
|
checkedAuth: boolean
|
10
|
}
|
11
|
|
12
|
const initialState: UserState = {
|
13
|
username: "",
|
14
|
loggedIn: false,
|
15
|
role: "",
|
16
|
checkedAuth: false
|
17
|
}
|
18
|
|
19
|
export const userSlice = createSlice({
|
20
|
name: "user",
|
21
|
initialState: initialState,
|
22
|
reducers: {
|
23
|
resetState: (state) => {
|
24
|
state = initialState
|
25
|
},
|
26
|
consumeError: (state) => {
|
27
|
state.lastError = undefined
|
28
|
}
|
29
|
},
|
30
|
extraReducers: (builder) => {
|
31
|
builder.addCase(login.fulfilled, (state, action) => {
|
32
|
state.username = action.payload.username
|
33
|
state.loggedIn = true
|
34
|
state.role = action.payload.role
|
35
|
state.lastError = undefined
|
36
|
})
|
37
|
builder.addCase(login.rejected, (state, action) => {
|
38
|
state.lastError = action.error.message
|
39
|
})
|
40
|
builder.addCase(checkAuth.fulfilled, (state, action) => {
|
41
|
state.loggedIn = action.payload.isLogged
|
42
|
state.lastError = undefined
|
43
|
state.checkedAuth = true
|
44
|
})
|
45
|
builder.addCase(checkAuth.rejected, (state, action) => {
|
46
|
state.lastError = action.error.message
|
47
|
state.checkedAuth = true
|
48
|
})
|
49
|
builder.addCase(logout.fulfilled, (state, action) => initialState)
|
50
|
}
|
51
|
})
|
52
|
|
53
|
export const { resetState, consumeError } = userSlice.actions
|
54
|
|
55
|
export default userSlice.reducer
|