From 936734f01b3b5db639d08bf21dfb359ce56bf062 Mon Sep 17 00:00:00 2001 From: andres Date: Fri, 2 Jun 2023 23:15:49 +0200 Subject: [PATCH] lesson 2 finished --- src/common/utils/create-thunk-action.ts | 15 +++++++++++++++ src/common/utils/index.ts | 1 + src/features/auth/auth.slice.ts | 18 +++--------------- 3 files changed, 19 insertions(+), 15 deletions(-) create mode 100644 src/common/utils/create-thunk-action.ts diff --git a/src/common/utils/create-thunk-action.ts b/src/common/utils/create-thunk-action.ts new file mode 100644 index 0000000..5dbb930 --- /dev/null +++ b/src/common/utils/create-thunk-action.ts @@ -0,0 +1,15 @@ +import { BaseThunkAPI } from "@reduxjs/toolkit/dist/createAsyncThunk" +import { AppDispatch, RootState } from "@/app/store" +import { thunkTryCatch } from "./" + +export const createThunkAction = ( + promise: (arg: A) => Promise, + transformPromise?: (arg: R) => T, +) => { + return ( + arg: A, + thunkAPI: BaseThunkAPI, + ) => { + return thunkTryCatch(thunkAPI, () => promise(arg).then(transformPromise)) + } +} diff --git a/src/common/utils/index.ts b/src/common/utils/index.ts index 1ea16f3..80bdb70 100644 --- a/src/common/utils/index.ts +++ b/src/common/utils/index.ts @@ -1,2 +1,3 @@ export * from "./create-app-async-thunk" export * from "./thunk-try-catch" +export * from "./create-thunk-action" diff --git a/src/features/auth/auth.slice.ts b/src/features/auth/auth.slice.ts index 023f953..c500d60 100644 --- a/src/features/auth/auth.slice.ts +++ b/src/features/auth/auth.slice.ts @@ -6,23 +6,11 @@ import { RegisterResponse, User, } from "@/features/auth/auth.api" -import { createAppAsyncThunk, thunkTryCatch } from "@/common" -import { BaseThunkAPI } from "@reduxjs/toolkit/dist/createAsyncThunk" -import { AppDispatch, RootState } from "@/app/store" +import { createAppAsyncThunk, createThunkAction } from "@/common" const THUNK_PREFIXES = { REGISTER: "auth/register", -} -const createThunkAction = ( - promise: (arg: A) => Promise, - transformPromise: (arg: R) => T, -) => { - return ( - arg: A, - thunkAPI: BaseThunkAPI, - ) => { - return thunkTryCatch(thunkAPI, () => promise(arg).then(transformPromise)) - } + LOGIN: "auth/login", } const register = createAppAsyncThunk<{ user: RegisterResponse }, RegisterArgs>( @@ -31,7 +19,7 @@ const register = createAppAsyncThunk<{ user: RegisterResponse }, RegisterArgs>( ) const login = createAppAsyncThunk<{ user: User }, LoginArgs>( - "auth/login", + THUNK_PREFIXES.LOGIN, createThunkAction(AuthApi.login, (res) => ({ user: res.data })), )