Projekt

Obecné

Profil

Stáhnout (2.04 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
    initialState, // default state
32
    // Reducers that update the state
33
    reducers: {
34
        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
        setUserState: (state, action) => ({ ...state, ...action.payload }),
45
        resetLoggingIn: (state) => ({ ...state, isLoggingIn: false }),
46
    },
47

    
48
    // Thunks
49
    extraReducers: (builder) => {
50
        builder.addCase(logIn.fulfilled, (state, action) => {
51
            return { ...state, ...action.payload }
52
        })
53
        builder.addCase(logIn.rejected, (state, action) => {
54
            if (action.payload && typeof action.error.message === 'string') {
55
                return { ...state, lastErr: action.error.message }
56
            }
57
        })
58
        builder.addCase(logIn.pending, (state) => {
59
            return { ...state, isLoggingIn: true }
60
        })
61
    },
62
})
63

    
64
const userReducer = persistReducer(persistConfig, userSlice.reducer)
65

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

    
69
export default userReducer
(6-6/7)