mirror of
https://github.com/ershisan99/cards-front.git
synced 2026-01-02 04:59:27 +00:00
part 4
This commit is contained in:
1
src/common/index.ts
Normal file
1
src/common/index.ts
Normal file
@@ -0,0 +1 @@
|
||||
export * from "./utils"
|
||||
8
src/common/utils/create-app-async-thunk.ts
Normal file
8
src/common/utils/create-app-async-thunk.ts
Normal file
@@ -0,0 +1,8 @@
|
||||
import { createAsyncThunk } from "@reduxjs/toolkit"
|
||||
import { AppDispatch, RootState } from "@/app/store"
|
||||
|
||||
export const createAppAsyncThunk = createAsyncThunk.withTypes<{
|
||||
state: RootState
|
||||
dispatch: AppDispatch
|
||||
rejectValue: unknown
|
||||
}>()
|
||||
1
src/common/utils/index.ts
Normal file
1
src/common/utils/index.ts
Normal file
@@ -0,0 +1 @@
|
||||
export * from "./create-app-async-thunk"
|
||||
@@ -1,44 +1,58 @@
|
||||
import { createAsyncThunk, createSlice, PayloadAction } from "@reduxjs/toolkit"
|
||||
import { createSlice, PayloadAction } from "@reduxjs/toolkit"
|
||||
import {
|
||||
AuthApi,
|
||||
LoginArgs,
|
||||
RegisterArgs,
|
||||
User,
|
||||
} from "@/features/auth/auth.api"
|
||||
import { createAppAsyncThunk } from "@/common"
|
||||
|
||||
const register = createAsyncThunk("auth/register", (arg: RegisterArgs) => {
|
||||
AuthApi.register(arg)
|
||||
.then((res) => {
|
||||
console.log(res)
|
||||
})
|
||||
.catch((res) => {
|
||||
console.error(res)
|
||||
})
|
||||
})
|
||||
const THUNK_PREFIXES = {
|
||||
REGISTER: "auth/register",
|
||||
}
|
||||
|
||||
const login = createAsyncThunk("auth/login", async (arg: LoginArgs) => {
|
||||
try {
|
||||
const register = createAppAsyncThunk<any, RegisterArgs>(
|
||||
THUNK_PREFIXES.REGISTER,
|
||||
(arg) => {
|
||||
AuthApi.register(arg)
|
||||
.then((res) => {
|
||||
console.log(res)
|
||||
})
|
||||
.catch((res) => {
|
||||
console.error(res)
|
||||
})
|
||||
},
|
||||
)
|
||||
|
||||
const login = createAppAsyncThunk<{ user: User }, LoginArgs>(
|
||||
"auth/login",
|
||||
async (arg) => {
|
||||
const res = await AuthApi.login(arg)
|
||||
return { user: res.data }
|
||||
} catch (e) {
|
||||
console.error(e)
|
||||
}
|
||||
})
|
||||
},
|
||||
)
|
||||
|
||||
const slice = createSlice({
|
||||
name: "auth",
|
||||
initialState: { user: null as User | null },
|
||||
initialState: { user: null as User | null, isLoading: false },
|
||||
reducers: {
|
||||
setUser: (state, action: PayloadAction<{ user: User }>) => {
|
||||
state.user = action.payload.user
|
||||
},
|
||||
},
|
||||
extraReducers: (builder) => {
|
||||
builder.addCase(login.pending, (state) => {
|
||||
state.isLoading = true
|
||||
})
|
||||
builder.addCase(login.fulfilled, (state, action) => {
|
||||
if (action.payload?.user) {
|
||||
state.user = action.payload.user
|
||||
state.isLoading = false
|
||||
}
|
||||
})
|
||||
builder.addCase(login.rejected, (state) => {
|
||||
state.isLoading = false
|
||||
})
|
||||
},
|
||||
})
|
||||
|
||||
|
||||
Reference in New Issue
Block a user