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

HT-7 1 and 3 Kostenevich #90

Open
wants to merge 1 commit into
base: master
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
30 changes: 20 additions & 10 deletions src/components/app/app.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,21 +4,31 @@ import Header from '../header';
import Basket from '../basket';
import { UserProvider } from '../../contexts/user-context';
import { useState } from 'react';
import orderErrorPage from '../orderErrorPage';
import { MoneyProvider } from '../../contexts/money-context';

const App = () => {
const [money, setMoney] = useState('USD');
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Не стоит данные контекста хранить в состоянии нашего приложения. Покажу как это можно сделать удобнее на своей домашке.

const [name, setName] = useState('Andrey');
return (
<div>
<UserProvider value={{ name, setName }}>
<Header />
<Switch>
<Redirect exact from="/" to="/restaurants" />
<Route path="/checkout" component={Basket} />
<Route path="/restaurants" component={Restaurants} />
<Route path="/error" component={() => <h2>Error Page!</h2>} />
<Route component={() => <h2>404 - Not found :(</h2>} />
</Switch>
</UserProvider>
<MoneyProvider value={{ money, setMoney }}>
<UserProvider value={{ name, setName }}>
<Header />
<Switch>
<Redirect exact from="/" to="/restaurants" />
<Route path="/checkout" component={Basket} />
<Route path="/restaurants" component={Restaurants} />
<Route path="/failedOrder" component={orderErrorPage} />
<Route path="/error" component={() => <h2>Error Page!</h2>} />
<Route
path="/successOrder"
component={() => <h2>Спасибо за заказ!</h2>}
/>
<Route component={() => <h2>404 - Not found :(</h2>} />
</Switch>
</UserProvider>
</MoneyProvider>
</div>
);
};
Expand Down
28 changes: 20 additions & 8 deletions src/components/basket/basket.js
Original file line number Diff line number Diff line change
@@ -1,16 +1,26 @@
import { connect } from 'react-redux';
import { Link } from 'react-router-dom';
import { CSSTransition, TransitionGroup } from 'react-transition-group';

import { sendOrderRequest } from '../../redux/actions';
import styles from './basket.module.css';
import './basket.css';
import itemStyles from './basket-item/basket-item.module.css';
import BasketItem from './basket-item';
import Button from '../button';
import { orderProductsSelector, totalSelector } from '../../redux/selectors';
import {
sendingBasketSelector,
orderProductsSelector,
totalSelector,
} from '../../redux/selectors';
import { UserConsumer } from '../../contexts/user-context';

function Basket({ title = 'Basket', total, orderProducts }) {
function Basket({
title = 'Basket',
total,
orderProducts,
sendOrderRequest,
sendingBasket,
}) {
// const { name } = useContext(userContext);

if (!total) {
Expand All @@ -20,9 +30,8 @@ function Basket({ title = 'Basket', total, orderProducts }) {
</div>
);
}

return (
<div className={styles.basket}>
<div className={sendingBasket ? styles.basketDisabled : styles.basket}>
<h4 className={styles.title}>
<UserConsumer>{({ name }) => `${name}'s ${title}`}</UserConsumer>
</h4>
Expand Down Expand Up @@ -53,7 +62,7 @@ function Basket({ title = 'Basket', total, orderProducts }) {
</div>
</div>
<Link to="/checkout">
<Button primary block>
<Button onClick={sendOrderRequest} primary block>
checkout
</Button>
</Link>
Expand All @@ -65,7 +74,10 @@ const mapStateToProps = (state) => {
return {
total: totalSelector(state),
orderProducts: orderProductsSelector(state),
sendingBasket: sendingBasketSelector(state),
};
};

export default connect(mapStateToProps)(Basket);
const mapDispatchToProps = {
sendOrderRequest,
};
export default connect(mapStateToProps, mapDispatchToProps)(Basket);
8 changes: 8 additions & 0 deletions src/components/basket/basket.module.css
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,14 @@
position: relative;
}

.basketDisabled {
padding: 13px 16px 20px;
background-color: var(--pink);
position: relative;
pointer-events: none;
opacity: 0.4;
}

.hr {
margin: 14px 0;
}
Expand Down
1 change: 1 addition & 0 deletions src/components/orderErrorPage/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export { default } from './orderErrorPage';
11 changes: 11 additions & 0 deletions src/components/orderErrorPage/orderErrorPage.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import { connect } from 'react-redux';
import { orderErrorSelector } from '../../redux/selectors';

function orderErrorPage({ orderError }) {
return <h2>{orderError}</h2>;
}

const mapStateToProps = (state) => ({
orderError: orderErrorSelector(state),
});
export default connect(mapStateToProps)(orderErrorPage);
11 changes: 8 additions & 3 deletions src/components/reviews/reviews.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import {
reviewsLoadedSelector,
usersLoadedSelector,
} from '../../redux/selectors';
import { CSSTransition, TransitionGroup } from 'react-transition-group';

const Reviews = ({
reviews,
Expand All @@ -29,9 +30,13 @@ const Reviews = ({

return (
<div className={styles.reviews}>
{reviews.map((id) => (
<Review key={id} id={id} />
))}
<TransitionGroup>
{reviews.map((id) => (
<CSSTransition key={id} timeout={500} classNames={{ ...styles }}>
<Review id={id} />
</CSSTransition>
))}
</TransitionGroup>
<ReviewForm restId={restId} />
</div>
);
Expand Down
8 changes: 8 additions & 0 deletions src/components/reviews/reviews.module.css
Original file line number Diff line number Diff line change
Expand Up @@ -4,3 +4,11 @@
max-width: 884px;
width: 100%;
}

.enter {
opacity: 0;
}
.enterActive {
opacity: 1;
transition: opacity 500ms, transform 500ms;
}
22 changes: 22 additions & 0 deletions src/contexts/money-context.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import { createContext } from 'react';

export const moneyContext = createContext('default');

export const rateList = {
USD: 1,
EUR: 0.87,
RUB: 71.45,
};

export const signList = {
USD: '$',
EUR: '€',
RUB: '₽',
};

export function moneyRate(moneyName, amount) {
return (moneyName * amount).toFixed(3);
}

export const MoneyProvider = moneyContext.Provider;
export const MoneyConsumer = moneyContext.Consumer;
35 changes: 35 additions & 0 deletions src/redux/actions.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,13 +12,15 @@ import {
REQUEST,
SUCCESS,
FAILURE,
SEND_ORDER,
} from './constants';

import {
usersLoadingSelector,
usersLoadedSelector,
reviewsLoadingSelector,
reviewsLoadedSelector,
productsToOrderSelector,
} from './selectors';

export const increment = (id) => ({ type: INCREMENT, id });
Expand Down Expand Up @@ -77,3 +79,36 @@ export const loadUsers = () => async (dispatch, getState) => {

dispatch(_loadUsers());
};

export const sendOrderRequest = () => async (dispatch, getState) => {
const state = getState();
if (state.router.location.pathname === '/checkout') {
dispatch({ type: SEND_ORDER + REQUEST });
try {
const result = await fetch('/api/order', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(productsToOrderSelector(state)),
});

const data = await result.json();

if (result.status === 400) {
const error = data;
dispatch({ type: SEND_ORDER + FAILURE, error });
dispatch(replace('/failedOrder'));
} else {
if (data === 'ok') {
dispatch({
type: SEND_ORDER + SUCCESS,
data,
});
dispatch(replace('/successOrder'));
}
}
} catch (error) {
dispatch({ type: SEND_ORDER + FAILURE, error });
dispatch(replace('/error'));
}
}
};
2 changes: 2 additions & 0 deletions src/redux/constants.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,3 +13,5 @@ export const LOAD_USERS = 'LOAD_USERS';
export const REQUEST = '_REQUEST';
export const SUCCESS = '_SUCCESS';
export const FAILURE = '_FAILURE';

export const SEND_ORDER = 'SEND_ORDER';
54 changes: 45 additions & 9 deletions src/redux/reducer/order.js
Original file line number Diff line number Diff line change
@@ -1,16 +1,52 @@
import { DECREMENT, INCREMENT, REMOVE } from '../constants';
import produce from 'immer';
import {
DECREMENT,
FAILURE,
INCREMENT,
REMOVE,
REQUEST,
SEND_ORDER,
SUCCESS,
} from '../constants';

// { [productId]: amount }
export default function (state = {}, action) {
const { type, id } = action;
const initialState = {
entities: {},
sending: false,
error: null,
text: '',
};

export default produce((draft = initialState, action) => {
const { type, id, data, error } = action;
switch (type) {
case INCREMENT:
return { ...state, [id]: (state[id] || 0) + 1 };
draft.entities[id] = (draft.entities[id] || 0) + 1;
break;
case DECREMENT:
return { ...state, [id]: state[id] > 0 ? (state[id] || 0) - 1 : 0 };
draft.entities[id] =
draft.entities[id] > 0 ? (draft.entities[id] || 0) - 1 : 0;
break;
case REMOVE:
return { ...state, [id]: 0 };
draft.entities[id] = 0;
break;
case SEND_ORDER + REQUEST:
draft.sending = true;
draft.error = null;
console.log(draft.sending);
break;
case SEND_ORDER + SUCCESS:
draft.sending = false;
draft.entities = {};
draft.error = null;
draft.text = data;
console.log(draft.sending);

break;
case SEND_ORDER + FAILURE:
draft.sending = false;
draft.error = error;
break;
default:
return state;
return draft;
}
}
});
19 changes: 18 additions & 1 deletion src/redux/selectors.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { createSelector } from 'reselect';

const restaurantsSelector = (state) => state.restaurants.entities;
const productsSelector = (state) => state.products.entities;
const orderSelector = (state) => state.order;
const orderSelector = (state) => state.order.entities;
const reviewsSelector = (state) => state.reviews.entities;
const usersSelector = (state) => state.users.entities;

Expand Down Expand Up @@ -88,3 +88,20 @@ export const averageRatingSelector = createSelector(
);
}
);

export const productsToOrderSelector = createSelector(
orderSelector,
(order) => {
const productsToOrderArray = Object.keys(order).map((key) => ({
id: key,
amount: order[key],
}));
return productsToOrderArray;
}
);

export const orderErrorSelector = (state) => {
return state.order.error;
};

export const sendingBasketSelector = (state) => state.order.sending;