Projekt

Obecné

Profil

Stáhnout (1.82 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
    isLoggedIn: boolean
12
    lastErr?: string // consumable for errors during thunks
13
}
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
        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) => {
45
            return ({ ...state, ...action.payload })
46
        },
47
    },
48

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

    
62

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

    
65
export const { logout, refreshTokens, setErr, setUserState } = userSlice.actions
66

    
67
export default userReducer
(3-3/4)