Projekt

Obecné

Profil

« Předchozí | Další » 

Revize 930b05fd

Přidáno uživatelem Schwobik před téměř 2 roky(ů)

adding redux for user state management

Zobrazit rozdíly:

src/stores/actions/userThunks.ts
1
import { createAsyncThunk } from "@reduxjs/toolkit"
2
import { axiosInstance } from "../../api/api"
3

  
4
export const login = createAsyncThunk(
5
    "user/login",
6
    async (payload: { username: string, password: string }, thunkAPI) => {
7
        const response = await axiosInstance.post(
8
            "/api/login",
9
            {
10
                username: payload.username,
11
                password: payload.password,
12
            }
13
        )
14
        if (response.status === 200) {
15
            return response.data
16
        } else {
17
            return Promise.reject(response.data ? response.data : "Login failed")
18
        }
19
    }
20
)
src/stores/reducers/userSlice.ts
1
import { createSlice } from "@reduxjs/toolkit"
2
import { login } from "../actions/userThunks"
3

  
4
export interface UserState {
5
    username: string
6
    loggedIn: boolean
7
    role: string
8
    lastError?: string
9
}
10

  
11
const initialState: UserState = {
12
    username: "",
13
    loggedIn: false,
14
    role: ""
15
}
16

  
17
export const userSlice = createSlice({
18
    name: "user",
19
    initialState: initialState,
20
    reducers: {
21
        logout: () => initialState,
22
    },
23
    extraReducers: (builder) => {
24
        builder.addCase(login.fulfilled, (state, action) => {
25
            state.username = action.payload.username
26
            state.loggedIn = true
27
            state.role = action.payload.role
28
            state.lastError = ""
29
        })
30
        builder.addCase(login.rejected, (state, action) => {
31
            state.lastError = action.error.message
32
        })
33
    }
34
})
35

  
36
export const { logout } = userSlice.actions
37

  
38
export default userSlice.reducer
src/stores/store.ts
1
import { configureStore } from "@reduxjs/toolkit"
2
import userReducer from "./reducers/userSlice"
3

  
4
export default configureStore({
5
    reducer: {
6
        user: userReducer,
7
    },
8
})

Také k dispozici: Unified diff