Projekt

Obecné

Profil

Stáhnout (1.44 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
        }
26 930b05fd Schwobik
    },
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 0efa284e Fantič
        builder.addCase(checkAuth.fulfilled, (state, action) => {
38
            state.loggedIn = action.payload.isLogged
39
            state.lastError = ""
40 06808454 Schwobik
            state.checkedAuth = true
41 0efa284e Fantič
        })
42
        builder.addCase(checkAuth.rejected, (state, action) => {
43
            state.lastError = action.error.message
44 06808454 Schwobik
            state.checkedAuth = true
45 0efa284e Fantič
        })
46 06808454 Schwobik
        builder.addCase(logout.fulfilled, (state, action) => initialState)
47 930b05fd Schwobik
    }
48
})
49
50 06808454 Schwobik
export const { resetState } = userSlice.actions
51 930b05fd Schwobik
52
export default userSlice.reducer