Projekt

Obecné

Profil

Stáhnout (2.05 KB) Statistiky
| Větev: | Tag: | Revize:
1
import { createSlice } from '@reduxjs/toolkit'
2
import { persistReducer } from 'redux-persist'
3
import storage from 'redux-persist/lib/storage'
4
import { logIn } from './userThunks'
5

    
6
export interface UserState {
7
    accessToken?: string
8
    refreshToken?: string
9
    username: string
10
    roles: string[]
11
    isLoggingIn: boolean
12
    isLoggedIn: boolean
13
    lastErr?: string // consumable for errors during thunks
14
}
15

    
16
const persistConfig = {
17
    key: 'auth',
18
    storage, // localStorage for browsers
19
}
20

    
21
// Default state when user first starts the application
22
const initialState: UserState = {
23
    roles: [],
24
    isLoggedIn: false,
25
    isLoggingIn: false,
26
    username: '',
27
}
28

    
29
export const userSlice = createSlice({
30
    name: 'user', // name to generate action types
31

    
32
    initialState, // default state
33

    
34
    // Reducers that update the state
35
    reducers: {
36
        logout: () => initialState, // Reset to the inital state
37
        refreshTokens: (state, action) => ({
38
            ...state,
39
            accessToken: action.payload.accessToken,
40
            refreshToken: action.payload.refreshToken,
41
        }),
42
        setErr: (state, action) => ({
43
            ...state,
44
            lastErr: action.payload,
45
        }),
46
        setUserState: (state, action) => ({ ...state, ...action.payload }),
47
        resetLoggingIn: (state) => ({ ...state, isLoggingIn: false }),
48
    },
49

    
50
    // Thunks
51
    extraReducers: (builder) => {
52
        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.error.message === 'string') {
57
                return { ...state, lastErr: action.error.message }
58
            }
59
        })
60
        builder.addCase(logIn.pending, (state, action) => {
61
            return { ...state, isLoggingIn: true }
62
        })
63
    },
64
})
65

    
66
const userReducer = persistReducer(persistConfig, userSlice.reducer)
67

    
68
export const { logout, refreshTokens, setErr, setUserState, resetLoggingIn } = userSlice.actions
69

    
70
export default userReducer
(6-6/7)