55 lines
1.3 KiB
TypeScript
55 lines
1.3 KiB
TypeScript
import { createAsyncThunk, createSlice } from "@reduxjs/toolkit";
|
|
import type { User } from "../../types/user.type";
|
|
import { Apis } from "../../apis";
|
|
import type { CartItem } from "../../types/cart.type";
|
|
|
|
|
|
interface UserState {
|
|
data: User | null,
|
|
loading: boolean;
|
|
cart: CartItem[] | []
|
|
}
|
|
|
|
const InitUserState: UserState = {
|
|
data: null,
|
|
loading: false,
|
|
cart: []
|
|
}
|
|
|
|
|
|
const userSlice = createSlice({
|
|
name: "user",
|
|
initialState: InitUserState,
|
|
reducers: {
|
|
initCartData: (state, action) =>{
|
|
state.cart = action.payload
|
|
}
|
|
},
|
|
extraReducers: (bd) => {
|
|
bd.addCase(fetchUserData.pending, (state, action) => {
|
|
state.loading = true
|
|
})
|
|
bd.addCase(fetchUserData.fulfilled, (state, action) => {
|
|
state.loading = false
|
|
state.data = action.payload
|
|
})
|
|
bd.addCase(fetchUserData.rejected, (state, action) => {
|
|
state.loading = false
|
|
})
|
|
}
|
|
})
|
|
|
|
|
|
const fetchUserData = createAsyncThunk(
|
|
"user/fetchUserData",
|
|
async () => {
|
|
let result = await Apis.user.me(localStorage.getItem("token")) as any
|
|
return result
|
|
}
|
|
)
|
|
|
|
export const userReducer = userSlice.reducer;
|
|
export const userAction = {
|
|
...userSlice.actions,
|
|
fetchUserData
|
|
} |