Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Refactor the large renderBody function of the cartPanel #1

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 28 additions & 0 deletions src/components/cart-panel/cart-item-list/index.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import { useContext } from 'react';

import { CartContext } from '../../../context/cart.context';

import CartItem from '../../cart-item';

const CartItemList = () => {
const { cartItems: items } = useContext(CartContext);

return (
<ul className="cart-panel__list">
{items.map((item, i) => (
<li key={item.id}>
<CartItem
title={item.title}
imageSrc={item.imageSrc}
index={i}
price={item.price}
currency={item.currency}
id={item.id}
/>
</li>
))}
</ul>
);
};

export default CartItemList;
121 changes: 55 additions & 66 deletions src/components/cart-panel/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,19 +3,42 @@ import axios from 'axios';
import cn from 'classnames';

import { AppContext } from '../../context/app.context';
import { CartContext, ICartContext } from '../../context/cart.context';
import { CartContext } from '../../context/cart.context';
import { API } from '../../utils/api';
import { formatRuPrice } from '../../utils/formatRuPrice';
import { SneakersItem } from '../../interfaces/sneakers.interface';

import CartItem from '../cart-item';
import InfoBlock from '../info-block';
import Button from '../button';
import CartItemList from './cart-item-list';

import './styles/cart-panel.scss';
import emptyBoxSrc from '../../assets/images/empty-box.png';
import orderConfirmedSrc from '../../assets/images/order-confirmed.png';

const renderNoItems = (isOrderConfirmed: boolean, closeCartPanel: () => void, orderData: OrderData | null, ) => {
if (isOrderConfirmed) {
return (
<InfoBlock
className="cart-panel__order-confirmed"
title={'Заказ оформлен!'}
description={`Ваш заказ #${orderData?.id} скоро будет передан курьерской доставке`}
imageData={{ src: orderConfirmedSrc, width: 83, height: 120 }}
onButtonClick={closeCartPanel}
/>
);
}

return (
<InfoBlock
title={'Корзина пустая'}
description={'Добавьте хотя бы одну пару кроссовок, чтобы сделать заказ.'}
imageData={{ src: emptyBoxSrc, width: 120, height: 120 }}
onButtonClick={closeCartPanel}
/>
);
};

interface CartPanelProps {
isOpened: boolean,
close: () => void,
Expand All @@ -29,68 +52,6 @@ interface OrderData {
items: SneakersItem[],
}

// todo: refactor
const renderCartPanelBody = (
items: ICartContext['cartItems'],
isOrderConfirmed: boolean,
handleCartButtonClick: () => void,
close: CartPanelProps['close'],
orderData: OrderData | null,
isLoading: boolean,
totalPrice: number
) => {
if (items.length > 0) {
return <>
<ul className="cart-panel__list">
{items.map((item, i) => (
<li key={item.id}>
<CartItem
title={item.title}
imageSrc={item.imageSrc}
index={i}
price={item.price}
currency={item.currency}
id={item.id}
/>
</li>
))}
</ul>
<div className="cart-panel__order-amount-and-tax-block">
<p className="cart-panel__row">
Итого:
<span className="dots"/>
<span>{formatRuPrice(totalPrice)}</span>
</p>
<p className="cart-panel__row" title="Сумма вернётся Вам на карту в течение 7 дней с момента оплаты">
Кэшбэк 5%:
<span className="dots"/>
<span>{formatRuPrice(Math.floor(totalPrice * 0.05))}</span>
</p>
</div>
<Button onClick={handleCartButtonClick} disabled={isLoading} arrowDirection="right">
Оформить заказ
</Button>
</>;
}

if (isOrderConfirmed) {
return <InfoBlock
className="cart-panel__order-confirmed"
title={'Заказ оформлен!'}
description={`Ваш заказ #${orderData?.id} скоро будет передан курьерской доставке`}
imageData={{ src: orderConfirmedSrc, width: 83, height: 120 }}
onButtonClick={close}
/>;
}

return <InfoBlock
title={'Корзина пустая'}
description={'Добавьте хотя бы одну пару кроссовок, чтобы сделать заказ.'}
imageData={{ src: emptyBoxSrc, width: 120, height: 120 }}
onButtonClick={close}
/>;
};

const CartPanel = ({ isOpened, close }: CartPanelProps) => {
const { isLoading, showLoader, hideLoader } = useContext(AppContext);
const { cartItems: items, totalPrice, clearCart } = useContext(CartContext);
Expand All @@ -107,7 +68,12 @@ const CartPanel = ({ isOpened, close }: CartPanelProps) => {
clearCart();
setOrderData(data);

setTimeout(close, 10000);
setTimeout(() => {
close();
setTimeout(() => {
setIsOrderConfirmed(false);
}, 1000);
}, 10000);
} catch (err) {
alert('Не удалось оформить заказ :(');
console.error(err);
Expand All @@ -120,7 +86,30 @@ const CartPanel = ({ isOpened, close }: CartPanelProps) => {
<div className={cn('overlay', { 'overlay--visible': isOpened })} onClick={close}>
<section className={cn('cart-panel', { 'cart-panel--opened': isOpened })} onClick={evt => evt.stopPropagation()}>
<h2 className="cart-panel__title">Корзина</h2>
{renderCartPanelBody(items, isOrderConfirmed, handleCartButtonClick, close, orderData, isLoading, totalPrice)}

{items.length > 0
? (
<>
<CartItemList />
<div className="cart-panel__order-amount-and-tax-block">
<p className="cart-panel__row">
Итого:
<span className="dots"/>
<span>{formatRuPrice(totalPrice)}</span>
</p>
<p className="cart-panel__row" title="Сумма вернётся Вам на карту в течение 7 дней с момента оплаты">
Кэшбэк 5%:
<span className="dots"/>
<span>{formatRuPrice(Math.floor(totalPrice * 0.05))}</span>
</p>
</div>
<Button onClick={handleCartButtonClick} disabled={isLoading} arrowDirection="right">
Оформить заказ
</Button>
</>
)
: renderNoItems(isOrderConfirmed, close, orderData)
}
</section>
</div>
);
Expand Down