49 lines
1.4 KiB
TypeScript
49 lines
1.4 KiB
TypeScript
import { addToCartApi, getCartApi, updateCartItem } from '@api';
|
|
import { AddToCartRequest, CartResponse } from '@interfaces/cart';
|
|
import { createAsyncThunk } from '@reduxjs/toolkit';
|
|
|
|
export const addToCartThunk = createAsyncThunk<CartResponse, AddToCartRequest>(
|
|
'cart/addToCart',
|
|
async (addToCartRequest, { rejectWithValue }) => {
|
|
try {
|
|
const response = await addToCartApi(addToCartRequest);
|
|
return response;
|
|
} catch (error: any) {
|
|
const message =
|
|
error instanceof Error ? error.message : 'Failed to add to cart';
|
|
return rejectWithValue(message);
|
|
}
|
|
},
|
|
);
|
|
|
|
export const getCartThunk = createAsyncThunk<CartResponse>(
|
|
'cart/getCart',
|
|
async (_, { rejectWithValue }) => {
|
|
try {
|
|
const response = await getCartApi();
|
|
return response;
|
|
} catch (error: any) {
|
|
const message =
|
|
error instanceof Error ? error.message : 'Failed to get cart';
|
|
return rejectWithValue(message);
|
|
}
|
|
},
|
|
);
|
|
|
|
export const updateCartItemThunk = createAsyncThunk<
|
|
CartResponse,
|
|
{ productId: string; quantity: number }
|
|
>(
|
|
'cart/updateCartItem',
|
|
async ({ productId, quantity }, { rejectWithValue }) => {
|
|
try {
|
|
const response = await updateCartItem(productId, quantity);
|
|
return response;
|
|
} catch (error: any) {
|
|
const message =
|
|
error instanceof Error ? error.message : 'Failed to update cart item';
|
|
return rejectWithValue(message);
|
|
}
|
|
},
|
|
);
|