Projekt

Obecné

Profil

Stáhnout (1.88 KB) Statistiky
| Větev: | Tag: | Revize:
1 37f6ff02 Vaclav Honzik
import { createSlice, PayloadAction } from '@reduxjs/toolkit'
2
import { persistReducer } from 'redux-persist'
3
import storage from 'redux-persist/lib/storage'
4 8370b6c1 Vaclav Honzik
import { logIn } from './userThunks'
5 37f6ff02 Vaclav Honzik
6
export interface UserState {
7
    accessToken?: string
8
    refreshToken?: string
9
    username: string
10
    roles: string[]
11
    isLoggedIn: boolean
12 8370b6c1 Vaclav Honzik
    lastErr?: string // consumable for errors during thunks
13 37f6ff02 Vaclav Honzik
}
14
15
const persistConfig = {
16
    key: 'auth',
17
    storage, // localStorage for browsers
18
}
19
20
// Default state when user first starts the application
21
const initialState: UserState = {
22
    roles: [],
23
    isLoggedIn: false,
24
    username: '',
25
}
26
27
export const userSlice = createSlice({
28
    name: 'user', // name to generate action types
29
30
    initialState, // default state
31
32
    // Reducers that update the state
33
    reducers: {
34 8370b6c1 Vaclav Honzik
        logout: () => initialState, // Reset to the inital state
35
        refreshTokens: (state, action) => ({
36
            ...state,
37
            accessToken: action.payload.accessToken,
38
            refreshToken: action.payload.refreshToken,
39
        }),
40
        setErr: (state, action) => ({
41
            ...state,
42
            lastErr: action.payload,
43
        }),
44 fc79a8cb Vaclav Honzik
        setUserState: (state, action) => {
45
            console.log('user state set')
46
            return ({ ...state, ...action.payload })
47
        },
48 37f6ff02 Vaclav Honzik
    },
49
50 8370b6c1 Vaclav Honzik
    // Thunks
51
    extraReducers: (builder) => {
52 fc79a8cb Vaclav Honzik
        builder.addCase(logIn.fulfilled, (state, action) => {
53
            return ({ ...state, ...action.payload })
54
        })
55
        builder.addCase(logIn.rejected, (state, action) => {
56
            if (action.payload && typeof action.payload === 'string') {
57
                return ({ ...state, lastErr: action.payload })
58
            }
59
        })
60 8370b6c1 Vaclav Honzik
    },
61 37f6ff02 Vaclav Honzik
})
62
63
const userReducer = persistReducer(persistConfig, userSlice.reducer)
64 8370b6c1 Vaclav Honzik
65 fc79a8cb Vaclav Honzik
export const { logout, refreshTokens, setErr, setUserState } = userSlice.actions
66
67 37f6ff02 Vaclav Honzik
export default userReducer