Projekt

Obecné

Profil

Stáhnout (1.2 KB) Statistiky
| Větev: | Tag: | Revize:
1
import { createSlice } from "@reduxjs/toolkit"
2
import { checkAuth, 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
        builder.addCase(checkAuth.fulfilled, (state, action) => {
34
            state.loggedIn = action.payload.isLogged
35
            state.lastError = ""
36
        })
37
        builder.addCase(checkAuth.rejected, (state, action) => {
38
            state.lastError = action.error.message
39
        })
40
    }
41
})
42

    
43
export const { logout } = userSlice.actions
44

    
45
export default userSlice.reducer
(2-2/2)