part 3 extra reducers

This commit is contained in:
andres
2023-05-26 21:32:42 +02:00
parent 38d3801914
commit eacb1623ca
9 changed files with 116 additions and 7 deletions

View File

@@ -1,7 +1,38 @@
import { AuthInstance } from "@/features/auth/auth.instance"
export const AuthApi = () => ({
register: (params: any) => {
return AuthInstance.post(params)
export const AuthApi = {
register: (params: RegisterArgs) => {
return AuthInstance.post<RegisterResponse>("register", params)
},
})
login: (params: LoginArgs) => {
return AuthInstance.post<User>("login", params)
},
}
export type RegisterResponse = {
addedUser: AddedUser
}
type PasswordToPick = {
password: string
}
export type AddedUser = Omit<User, "token" | "tokenDeathTime">
export type RegisterArgs = Pick<User, "email"> & PasswordToPick
export type LoginArgs = Pick<User, "email" | "rememberMe"> & PasswordToPick
export type PartialUser = Partial<User>
export type User = {
_id: string
email: string
rememberMe: boolean
isAdmin: boolean
name: string
verified: boolean
publicCardPacksCount: number
created: string
updated: string
token: string
tokenDeathTime: number
__v: number
}

View File

@@ -1,6 +1,6 @@
import axios from "axios"
export const AuthInstance = axios.create({
baseURL: import.meta.env.BASE_URL + "auth/",
baseURL: import.meta.env.VITE_BASE_API_URL + "auth/",
withCredentials: true,
})

View File

@@ -0,0 +1,46 @@
import { createAsyncThunk, createSlice, PayloadAction } from "@reduxjs/toolkit"
import {
AuthApi,
LoginArgs,
RegisterArgs,
User,
} from "@/features/auth/auth.api"
const register = createAsyncThunk("auth/register", (arg: RegisterArgs) => {
AuthApi.register(arg)
.then((res) => {
console.log(res)
})
.catch((res) => {
console.error(res)
})
})
const login = createAsyncThunk("auth/login", async (arg: LoginArgs) => {
try {
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 },
reducers: {
setUser: (state, action: PayloadAction<{ user: User }>) => {
state.user = action.payload.user
},
},
extraReducers: (builder) => {
builder.addCase(login.fulfilled, (state, action) => {
if (action.payload?.user) {
state.user = action.payload.user
}
})
},
})
export const authReducer = slice.reducer
export const authThunks = { register, login }