Projekt

Obecné

Profil

Stáhnout (1.56 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
export interface UserState {
5
    username: string
6
    loggedIn: boolean
7
    role: string
8
    lastError?: string
9 06808454 Schwobik
    checkedAuth: boolean
10 930b05fd Schwobik
}
11
12
const initialState: UserState = {
13
    username: "",
14
    loggedIn: false,
15 06808454 Schwobik
    role: "",
16
    checkedAuth: false
17 930b05fd Schwobik
}
18
19
export const userSlice = createSlice({
20
    name: "user",
21
    initialState: initialState,
22
    reducers: {
23 06808454 Schwobik
        resetState: (state) => {
24
            state = initialState
25 7410d6c1 Michal Schwob
        },
26
        consumeError: (state) => {
27
            state.lastError = undefined
28 06808454 Schwobik
        }
29 930b05fd Schwobik
    },
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 7410d6c1 Michal Schwob
            state.lastError = undefined
36 930b05fd Schwobik
        })
37
        builder.addCase(login.rejected, (state, action) => {
38
            state.lastError = action.error.message
39
        })
40 0efa284e Fantič
        builder.addCase(checkAuth.fulfilled, (state, action) => {
41
            state.loggedIn = action.payload.isLogged
42 7410d6c1 Michal Schwob
            state.lastError = undefined
43 06808454 Schwobik
            state.checkedAuth = true
44 0efa284e Fantič
        })
45
        builder.addCase(checkAuth.rejected, (state, action) => {
46
            state.lastError = action.error.message
47 06808454 Schwobik
            state.checkedAuth = true
48 0efa284e Fantič
        })
49 06808454 Schwobik
        builder.addCase(logout.fulfilled, (state, action) => initialState)
50 930b05fd Schwobik
    }
51
})
52
53 7410d6c1 Michal Schwob
export const { resetState, consumeError } = userSlice.actions
54 930b05fd Schwobik
55
export default userSlice.reducer