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

Ershovro/homework 7 #86

Open
wants to merge 4 commits 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
4 changes: 4 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -21,3 +21,7 @@ node_modules
npm-debug.log*
yarn-debug.log*
yarn-error.log*


.idea
package-lock.json
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@
"web-vitals": "^0.2.4"
},
"scripts": {
"start": "concurrently \"react-scripts start\" \"yarn api\"",
"start": "concurrently \"react-scripts start\" \"npm run api\"",
"api": "node simple_api/server.js",
"build": "react-scripts build",
"test": "react-scripts test",
Expand Down
38 changes: 27 additions & 11 deletions src/components/app/app.js
Original file line number Diff line number Diff line change
@@ -1,23 +1,39 @@
import React, { useState } from 'react';
import { Route, Switch } from 'react-router-dom';
import React, { useState, useContext } from 'react';
import { Route, Switch, Redirect } from 'react-router-dom';
import Header from '../header';
import Basket from '../basket';
import RestaurantsPage from '../../pages/restaurants-page';
import OrderSuccessPage from '../../pages/order-success-page';
import ErrorPage from '../../pages/error-page';
import { UserProvider } from '../../contexts/user-context';
import currencyContext, {
CurrencyProvider,
} from '../../contexts/currency-context';

const App = () => {
const { currency: initialCurrency, ...restCurrencyContextData } = useContext(
currencyContext
);
const [name, setName] = useState('Igor');
const [currency, setCurrency] = useState(initialCurrency);

return (
<div>
<UserProvider value={{ name, setName }}>
<Header />
<Switch>
<Route path="/checkout" component={Basket} />
<Route path="/restaurants" component={RestaurantsPage} />
<Route path="/error" component={() => <h1>Error Page</h1>} />
<Route path="/" component={() => '404 - not found'} />
</Switch>
</UserProvider>
<CurrencyProvider
value={{ ...restCurrencyContextData, currency, setCurrency }}
>
<UserProvider value={{ name, setName }}>
<Header />
<Switch>
<Redirect exact from="/" to="/restaurants" />
<Route path="/checkout" component={Basket} />
<Route path="/restaurants" component={RestaurantsPage} />
<Route path="/order-success" component={OrderSuccessPage} />
<Route path="/error" component={ErrorPage} />
<Route path="/" component={() => '404 - not found'} />
</Switch>
</UserProvider>
</CurrencyProvider>
</div>
);
};
Expand Down
7 changes: 6 additions & 1 deletion src/components/basket/basket-item/basket-item.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { connect } from 'react-redux';
import { Link } from 'react-router-dom';
import cn from 'classnames';
import { increment, decrement, remove } from '../../../redux/actions';
import { CurrencyConsumer } from '../../../contexts/currency-context';
import Button from '../../button';
import styles from './basket-item.module.css';

Expand Down Expand Up @@ -38,7 +39,11 @@ function BasketItem({
small
/>
</div>
<p className={cn(styles.count, styles.price)}>{subtotal} $</p>
<p className={cn(styles.count, styles.price)}>
<CurrencyConsumer>
{({ convert, currency }) => convert(subtotal, currency)}
</CurrencyConsumer>
</p>
<Button
onClick={() => remove(product.id)}
icon="delete"
Expand Down
45 changes: 38 additions & 7 deletions src/components/basket/basket.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,11 +10,26 @@ import './basket.css';
import BasketRow from './basket-row';
import BasketItem from './basket-item';
import Button from '../button';
import { orderProductsSelector, totalSelector } from '../../redux/selectors';
import {
orderProductsSelector,
totalSelector,
checkoutProcessingSelector,
} from '../../redux/selectors';
import { UserConsumer } from '../../contexts/user-context';
import { CurrencyConsumer } from '../../contexts/currency-context';
import { checkout } from '../../redux/actions';
import Loader from '../loader';

function Basket({ title = 'Basket', total, orderProducts }) {
// const { name } = useContext(userContext);
function Basket({
title = 'Basket',
total,
orderProducts,
onCheckout = (f) => f,
processing,
}) {
if (processing) {
return <Loader />;
}

if (!total) {
return (
Expand Down Expand Up @@ -47,11 +62,26 @@ function Basket({ title = 'Basket', total, orderProducts }) {
))}
</TransitionGroup>
<hr className={styles.hr} />
<BasketRow label="Sub-total" content={`${total} $`} />
<BasketRow
label="Sub-total"
content={
<CurrencyConsumer>
{({ convert, currency }) => convert(total, currency)}
</CurrencyConsumer>
}
/>
<BasketRow label="Delivery costs:" content="FREE" />
<BasketRow label="total" content={`${total} $`} bold />
<BasketRow
label="total"
content={
<CurrencyConsumer>
{({ convert, currency }) => convert(total, currency)}
</CurrencyConsumer>
}
bold
/>
<Link to="/checkout">
<Button primary block>
<Button onClick={onCheckout} primary block>
checkout
</Button>
</Link>
Expand All @@ -62,6 +92,7 @@ function Basket({ title = 'Basket', total, orderProducts }) {
const mapStateToProps = createStructuredSelector({
total: totalSelector,
orderProducts: orderProductsSelector,
processing: checkoutProcessingSelector,
});

export default connect(mapStateToProps)(Basket);
export default connect(mapStateToProps, { onCheckout: checkout })(Basket);
14 changes: 14 additions & 0 deletions src/components/header/header.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,26 @@ import React, { useContext } from 'react';
import Logo from './logo';
import styles from './header.module.css';
import userContext from '../../contexts/user-context';
import currencyContext from '../../contexts/currency-context';

const Header = () => {
const { name, setName } = useContext(userContext);
const { currency, setCurrency, dictionary } = useContext(currencyContext);

return (
<header className={styles.header} onClick={() => setName('Ivan')}>
<select
value={currency}
onChange={(event) => {
setCurrency(event.target.value);
}}
>
{Object.keys(dictionary).map((name, i) => (
<option key={i} value={name}>
{name}
</option>
))}
</select>
<Logo />
<h2>{name}</h2>
</header>
Expand Down
5 changes: 5 additions & 0 deletions src/components/header/header.module.css
Original file line number Diff line number Diff line change
Expand Up @@ -13,3 +13,8 @@
right: 20px;
top: 0;
}

.header select {
position: absolute;
left: 20px;
}
8 changes: 7 additions & 1 deletion src/components/product/product.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import { decrement, increment } from '../../redux/actions';

import Button from '../button';
import { productAmountSelector, productSelector } from '../../redux/selectors';
import { CurrencyConsumer } from '../../contexts/currency-context';

const Product = ({ product, amount = 0, increment, decrement }) => {
if (!product) return null;
Expand All @@ -18,7 +19,12 @@ const Product = ({ product, amount = 0, increment, decrement }) => {
<div>
<h4 className={styles.title}>{product.name}</h4>
<p className={styles.description}>{product.ingredients.join(', ')}</p>
<div className={styles.price}>{product.price} $</div>
<div className={styles.price}>
{' '}
<CurrencyConsumer>
{({ convert, currency }) => convert(product.price, currency)}
</CurrencyConsumer>
</div>
</div>
<div>
<div className={styles.counter}>
Expand Down
18 changes: 15 additions & 3 deletions src/components/reviews/reviews.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import Review from './review';
import ReviewForm from './review-form';
import styles from './reviews.module.css';
import { connect } from 'react-redux';
import { TransitionGroup, CSSTransition } from 'react-transition-group';

import { loadReviews, loadUsers } from '../../redux/actions';
import {
Expand All @@ -31,9 +32,20 @@ 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={{
enter: styles['review-animation-enter'],
enterActive: styles['review-animation-enter-active'],
}}
>
<Review id={id} />
</CSSTransition>
))}
</TransitionGroup>
<ReviewForm restaurantId={restaurantId} />
</div>
);
Expand Down
11 changes: 11 additions & 0 deletions src/components/reviews/reviews.module.css
Original file line number Diff line number Diff line change
Expand Up @@ -4,3 +4,14 @@
max-width: 884px;
width: 100%;
}

.review-animation-enter {
opacity: 0;
transform: scale(0.9);
}

.review-animation-enter-active {
opacity: 1;
transform: translateX(0);
transition: opacity 500ms, transform 500ms;
}
21 changes: 21 additions & 0 deletions src/contexts/currency-context.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import { createContext } from 'react';

const dictionary = {
$: 1,
'₽': 73.09,
'€': 0.82,
};

const convert = (priceInDollars, toCurrency) =>
`${Math.round(priceInDollars * dictionary[toCurrency])}${toCurrency}`;

const currencyContext = createContext({
currency: '$',
dictionary,
convert,
});

export const CurrencyConsumer = currencyContext.Consumer;
export const CurrencyProvider = currencyContext.Provider;

export default currencyContext;
8 changes: 8 additions & 0 deletions src/pages/error-page.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import React from 'react';
import { connect } from 'react-redux';

const errorPage = ({ title = 'error page' }) => <h1>{title}</h1>;

export default connect((state) => ({
title: state.router.location.state,
}))(errorPage);
5 changes: 5 additions & 0 deletions src/pages/order-success-page.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import React from 'react';

const OrderSuccessPage = () => <h1>Thank you for the order!</h1>;

export default OrderSuccessPage;
26 changes: 15 additions & 11 deletions src/pages/restaurants-page.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import React, { useEffect } from 'react';
import { Route } from 'react-router-dom';
import { Route, Switch, Redirect } from 'react-router-dom';
import { connect } from 'react-redux';
import { createStructuredSelector } from 'reselect';
import Restaurants from '../components/restaurants';
Expand All @@ -12,23 +12,27 @@ import {

import { loadRestaurants } from '../redux/actions';

function RestaurantsPage({ loadRestaurants, loading, loaded, match }) {
function RestaurantsPage({
restaurants,
loadRestaurants,
loading,
loaded,
match,
}) {
useEffect(() => {
if (!loading && !loaded) loadRestaurants();
}, []); // eslint-disable-line

if (loading || !loaded) return <Loader />;

if (match.isExact) {
return (
<>
<Restaurants match={match} />
<h2 style={{ textAlign: 'center' }}>Select restaurant</h2>
</>
);
}
const [{ id: firstRestId }] = restaurants;

return <Route path="/restaurants/:restId" component={Restaurants} />;
return (
<Switch>
<Redirect exact from="/restaurants" to={`/restaurants/${firstRestId}`} />
<Route path="/restaurants/:restId" component={Restaurants} />
</Switch>
);
}

export default connect(
Expand Down
29 changes: 28 additions & 1 deletion src/redux/actions.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { replace } from 'connected-react-router';
import { replace, push } from 'connected-react-router';
import {
INCREMENT,
DECREMENT,
Expand All @@ -8,6 +8,7 @@ import {
LOAD_REVIEWS,
LOAD_PRODUCTS,
LOAD_USERS,
CHECKOUT,
REQUEST,
SUCCESS,
FAILURE,
Expand All @@ -17,6 +18,7 @@ import {
usersLoadedSelector,
reviewsLoadingSelector,
reviewsLoadedSelector,
checkoutSelector,
} from './selectors';

export const increment = (id) => ({ type: INCREMENT, payload: { id } });
Expand Down Expand Up @@ -67,3 +69,28 @@ export const loadUsers = () => async (dispatch, getState) => {

dispatch({ type: LOAD_USERS, CallAPI: '/api/users' });
};

export const checkout = () => async (dispatch, getState) => {
//const
dispatch({ type: CHECKOUT + REQUEST });

try {
const state = getState();
const order = checkoutSelector(state);
const response = await fetch('/api/order', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(order),
});

if (response.ok) {
dispatch({ type: CHECKOUT + SUCCESS });
dispatch(push('/order-success'));
} else {
throw await response.json();
}
} catch (error) {
dispatch({ type: CHECKOUT + FAILURE });
dispatch(push('/error', error));
}
};
Loading