This commit is contained in:
andres
2023-05-26 22:06:57 +02:00
parent eacb1623ca
commit 47be10e445
6 changed files with 816 additions and 825 deletions

1
src/common/index.ts Normal file
View File

@@ -0,0 +1 @@
export * from "./utils"

View 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
}>()

View File

@@ -0,0 +1 @@
export * from "./create-app-async-thunk"

View File

@@ -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
})
},
})