Projekt

Obecné

Profil

Stáhnout (2.32 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, register} 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
    isRegistered: boolean
15
}
16

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

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

    
31
export const userSlice = createSlice({
32
    name: 'user', // name to generate action types
33
    initialState, // default state
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
        resetIsRegistered: (state) => ({ ...state, isRegistered: false }),
49
    },
50

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

    
70
const userReducer = persistReducer(persistConfig, userSlice.reducer)
71

    
72
export const { logout, refreshTokens, setErr, setUserState, resetLoggingIn, resetIsRegistered } =
73
    userSlice.actions
74

    
75
export default userReducer
(6-6/7)