Projekt

Obecné

Profil

Stáhnout (1.87 KB) Statistiky
| Větev: | Tag: | Revize:
1 930b05fd Schwobik
import { createSlice } from "@reduxjs/toolkit"
2 06808454 Schwobik
import { checkAuth, login, logout } from "../actions/userThunks"
3 930b05fd Schwobik
4 b56c1e7d Fantič
export enum UserRole {
5
    Admin = "admin",
6
    User = "user",
7
    Contributor = "contributor",
8
    Unauthorized = "unauthorized"
9
  }
10
11
12 930b05fd Schwobik
export interface UserState {
13
    username: string
14 b56c1e7d Fantič
    userId: string
15 930b05fd Schwobik
    loggedIn: boolean
16 b56c1e7d Fantič
    role: UserRole
17 930b05fd Schwobik
    lastError?: string
18 06808454 Schwobik
    checkedAuth: boolean
19 930b05fd Schwobik
}
20
21
const initialState: UserState = {
22
    username: "",
23 b56c1e7d Fantič
    userId: "",
24 930b05fd Schwobik
    loggedIn: false,
25 b56c1e7d Fantič
    role: UserRole.Unauthorized,
26 06808454 Schwobik
    checkedAuth: false
27 930b05fd Schwobik
}
28
29
export const userSlice = createSlice({
30
    name: "user",
31
    initialState: initialState,
32
    reducers: {
33 06808454 Schwobik
        resetState: (state) => {
34
            state = initialState
35 7410d6c1 Michal Schwob
        },
36
        consumeError: (state) => {
37
            state.lastError = undefined
38 06808454 Schwobik
        }
39 930b05fd Schwobik
    },
40
    extraReducers: (builder) => {
41
        builder.addCase(login.fulfilled, (state, action) => {
42
            state.username = action.payload.username
43 b56c1e7d Fantič
            state.userId = action.payload.userId
44 930b05fd Schwobik
            state.loggedIn = true
45
            state.role = action.payload.role
46 7410d6c1 Michal Schwob
            state.lastError = undefined
47 930b05fd Schwobik
        })
48
        builder.addCase(login.rejected, (state, action) => {
49
            state.lastError = action.error.message
50
        })
51 0efa284e Fantič
        builder.addCase(checkAuth.fulfilled, (state, action) => {
52
            state.loggedIn = action.payload.isLogged
53 7410d6c1 Michal Schwob
            state.lastError = undefined
54 b56c1e7d Fantič
            state.userId = action.payload.userId
55 06808454 Schwobik
            state.checkedAuth = true
56 0efa284e Fantič
        })
57
        builder.addCase(checkAuth.rejected, (state, action) => {
58
            state.lastError = action.error.message
59 06808454 Schwobik
            state.checkedAuth = true
60 ccb721de Michal Schwob
            state.loggedIn = false
61 0efa284e Fantič
        })
62 06808454 Schwobik
        builder.addCase(logout.fulfilled, (state, action) => initialState)
63 930b05fd Schwobik
    }
64
})
65
66 7410d6c1 Michal Schwob
export const { resetState, consumeError } = userSlice.actions
67 930b05fd Schwobik
68
export default userSlice.reducer