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
|
},
|
27
|
extraReducers: (builder) => {
|
28
|
builder.addCase(login.fulfilled, (state, action) => {
|
29
|
state.username = action.payload.username
|
30
|
state.loggedIn = true
|
31
|
state.role = action.payload.role
|
32
|
state.lastError = ""
|
33
|
})
|
34
|
builder.addCase(login.rejected, (state, action) => {
|
35
|
state.lastError = action.error.message
|
36
|
})
|
37
|
builder.addCase(checkAuth.fulfilled, (state, action) => {
|
38
|
state.loggedIn = action.payload.isLogged
|
39
|
state.lastError = ""
|
40
|
state.checkedAuth = true
|
41
|
})
|
42
|
builder.addCase(checkAuth.rejected, (state, action) => {
|
43
|
state.lastError = action.error.message
|
44
|
state.checkedAuth = true
|
45
|
})
|
46
|
builder.addCase(logout.fulfilled, (state, action) => initialState)
|
47
|
}
|
48
|
})
|
49
|
|
50
|
export const { resetState } = userSlice.actions
|
51
|
|
52
|
export default userSlice.reducer
|