1
|
import { createSlice } from "@reduxjs/toolkit"
|
2
|
import { login } from "../actions/userThunks"
|
3
|
|
4
|
export interface UserState {
|
5
|
username: string
|
6
|
loggedIn: boolean
|
7
|
role: string
|
8
|
lastError?: string
|
9
|
}
|
10
|
|
11
|
const initialState: UserState = {
|
12
|
username: "",
|
13
|
loggedIn: false,
|
14
|
role: ""
|
15
|
}
|
16
|
|
17
|
export const userSlice = createSlice({
|
18
|
name: "user",
|
19
|
initialState: initialState,
|
20
|
reducers: {
|
21
|
logout: () => initialState,
|
22
|
},
|
23
|
extraReducers: (builder) => {
|
24
|
builder.addCase(login.fulfilled, (state, action) => {
|
25
|
state.username = action.payload.username
|
26
|
state.loggedIn = true
|
27
|
state.role = action.payload.role
|
28
|
state.lastError = ""
|
29
|
})
|
30
|
builder.addCase(login.rejected, (state, action) => {
|
31
|
state.lastError = action.error.message
|
32
|
})
|
33
|
}
|
34
|
})
|
35
|
|
36
|
export const { logout } = userSlice.actions
|
37
|
|
38
|
export default userSlice.reducer
|