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

ДЗ7 #84

Open
wants to merge 3 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
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ node_modules
.env.development.local
.env.test.local
.env.production.local
.idea

npm-debug.log*
yarn-debug.log*
Expand Down
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
"prop-types": "^15.7.2",
"react": "^17.0.1",
"react-dom": "^17.0.1",
"react-dropdown-select": "^4.7.1",
"react-redux": "^7.2.2",
"react-router-dom": "^5.2.0",
"react-scripts": "4.0.0",
Expand Down
16 changes: 9 additions & 7 deletions src/components/app/app.js
Original file line number Diff line number Diff line change
@@ -1,23 +1,25 @@
import React, { useState } from 'react';
import { Route, Switch } from 'react-router-dom';
import { Redirect, Route, Switch } from 'react-router-dom';
import Header from '../header';
import Basket from '../basket';
import RestaurantsPage from '../../pages/restaurants-page';
import { UserProvider } from '../../contexts/user-context';
import ErrorPage from '../../pages/error-page';
import { CurrencyProvider } from '../../contexts/currency-context';

const App = () => {
const [name, setName] = useState('Igor');
const [currency, setCurrency] = useState('USD');
return (
<div>
<UserProvider value={{ name, setName }}>
<CurrencyProvider value={{ currency, setCurrency }}>
<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'} />
<Route path="/error" component={ErrorPage} />
<Route path="/success" component={() => <h1>Thanks for order!</h1>} />
<Redirect from="/" to="/restaurants" />
Copy link
Owner

Choose a reason for hiding this comment

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

Redirect с рута лучше ставить самым первым, так мы сразу понимаем, что происходит при первом заходе на /

</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 @@ -5,6 +5,7 @@ import cn from 'classnames';
import { increment, decrement, remove } from '../../../redux/actions';
import Button from '../../button';
import styles from './basket-item.module.css';
import { CurrencyConsumer } from '../../../contexts/currency-context';

function BasketItem({
product,
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>
Copy link
Owner

Choose a reason for hiding this comment

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

не самы удобный АПИ получается у фунции конвертации, покажу как удобнее на своей домашке

{({ currency }) => `${subtotal} ${currency}`}
</CurrencyConsumer>
</p>
<Button
onClick={() => remove(product.id)}
icon="delete"
Expand Down
7 changes: 6 additions & 1 deletion src/components/basket/basket-row/basket-row.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import React from 'react';
import cx from 'classnames';
import styles from '../basket-item/basket-item.module.css';
import { CurrencyConsumer } from '../../../contexts/currency-context';

function BasketRow({ label, content, bold = false }) {
return (
Expand All @@ -9,7 +10,11 @@ function BasketRow({ label, content, bold = false }) {
<p className={cx({ [styles.bold]: bold })}>{label}</p>
</div>
<div className={styles.info}>
<p className={cx({ [styles.bold]: bold })}>{content}</p>
<p className={cx({ [styles.bold]: bold })}>
<CurrencyConsumer>
{(value) => `${content} ${value.currency}`}
</CurrencyConsumer>
</p>
</div>
</div>
);
Expand Down
43 changes: 35 additions & 8 deletions src/components/basket/basket.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import React from 'react';
import React, { useCallback } from 'react';
import { connect } from 'react-redux';
import { Link } from 'react-router-dom';
import { createStructuredSelector } from 'reselect';
Expand All @@ -10,11 +10,31 @@ import './basket.css';
import BasketRow from './basket-row';
import BasketItem from './basket-item';
import Button from '../button';
import { orderProductsSelector, totalSelector } from '../../redux/selectors';
import { checkout } from '../../redux/actions';
import {
checkoutOrderProductsSelector,
orderProductsSelector,
currentRouteSelector,
orderSavingSelector,
totalSelector,
} from '../../redux/selectors';
import { UserConsumer } from '../../contexts/user-context';
import Loader from '../loader';

function Basket({ title = 'Basket', total, orderProducts }) {
// const { name } = useContext(userContext);
function Basket({
title = 'Basket',
total,
orderProducts,
checkoutProducts,
route,
checkout,
saving,
}) {
const onClickHandler = useCallback(() => {
if (route === '/checkout') {
checkout(checkoutProducts);
}
}, [checkoutProducts, route, checkout]);

if (!total) {
return (
Expand All @@ -24,6 +44,10 @@ function Basket({ title = 'Basket', total, orderProducts }) {
);
}

if (saving) {
return <Loader />;
}

return (
<div className={styles.basket}>
{/* <h4 className={styles.title}>{`${name}'s ${title}`}</h4> */}
Expand All @@ -47,11 +71,11 @@ function Basket({ title = 'Basket', total, orderProducts }) {
))}
</TransitionGroup>
<hr className={styles.hr} />
<BasketRow label="Sub-total" content={`${total} $`} />
<BasketRow label="Sub-total" content={total} />
<BasketRow label="Delivery costs:" content="FREE" />
<BasketRow label="total" content={`${total} $`} bold />
<BasketRow label="total" content={total} bold />
<Link to="/checkout">
<Button primary block>
<Button primary block onClick={onClickHandler}>
checkout
</Button>
</Link>
Expand All @@ -61,7 +85,10 @@ function Basket({ title = 'Basket', total, orderProducts }) {

const mapStateToProps = createStructuredSelector({
total: totalSelector,
saving: orderSavingSelector,
route: currentRouteSelector,
orderProducts: orderProductsSelector,
checkoutProducts: checkoutOrderProductsSelector,
});

export default connect(mapStateToProps)(Basket);
export default connect(mapStateToProps, { checkout })(Basket);
33 changes: 33 additions & 0 deletions src/components/header/currency-select/currency-select.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import React, { useMemo, useContext, useState } from 'react';
import Select from 'react-dropdown-select';
import CurrencyContext from '../../../contexts/currency-context';
import CURRENCIES from '../../../constants/currencies';

const CurrencySelect = ({ className }) => {
const { setCurrency } = useContext(CurrencyContext);
const options = useMemo(
() =>
Object.keys(CURRENCIES).map((currency) => ({
value: currency,
label: currency,
})),
[]
);
const [selectedOption, setSelectedOption] = useState([options[0]]);
Copy link
Owner

Choose a reason for hiding this comment

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

это лишнее состояние, можно взять currency из CurrencyContext


const handleOnChange = (value) => {
setSelectedOption(value);
setCurrency(value[0]?.value);
};

return (
<Select
onChange={handleOnChange}
className={className}
options={options}
values={selectedOption}
/>
);
};

export default CurrencySelect;
1 change: 1 addition & 0 deletions src/components/header/currency-select/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export { default } from './currency-select';
18 changes: 8 additions & 10 deletions src/components/header/header.js
Original file line number Diff line number Diff line change
@@ -1,17 +1,15 @@
import React, { useContext } from 'react';
import React from 'react';

import Logo from './logo';
import CurrencySelect from './currency-select';
import styles from './header.module.css';
import userContext from '../../contexts/user-context';

const Header = () => {
const { name, setName } = useContext(userContext);

return (
<header className={styles.header} onClick={() => setName('Ivan')}>
const Header = () => (
<div className={styles.wrapper}>
<header className={styles.header}>
<Logo />
<h2>{name}</h2>
</header>
);
};
<CurrencySelect className={styles.currency} />
</div>
);
export default Header;
15 changes: 9 additions & 6 deletions src/components/header/header.module.css
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,16 @@
align-items: center;
justify-content: center;
height: 60px;
background: var(--black);
position: relative;
flex-grow: 10;
}

.currency {
background-color: var(--white);
}

.header h2 {
position: absolute;
color: var(--white);
right: 20px;
top: 0;
.wrapper {
display: flex;
align-items: center;
background: var(--black);
}
8 changes: 8 additions & 0 deletions src/constants/currencies.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
const CURRENCIES = {
USD: 1,
RUB: 73,
UAH: 28,
JPY: 104,
};

export default CURRENCIES;
8 changes: 8 additions & 0 deletions src/contexts/currency-context.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import { createContext } from 'react';

const currencyContext = createContext({});

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

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

function ErrorPage({ error }) {
return (
<>
<h1>Error Page</h1>
<p>{error}</p>
</>
);
}

export default connect(
createStructuredSelector({
error: currentErrorRouteSelector,
})
)(ErrorPage);
19 changes: 11 additions & 8 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 { Redirect, Route } from 'react-router-dom';
import { connect } from 'react-redux';
import { createStructuredSelector } from 'reselect';
import Restaurants from '../components/restaurants';
Expand All @@ -8,31 +8,34 @@ import {
restaurantsListSelector,
restaurantsLoadedSelector,
restaurantsLoadingSelector,
firstRestaurantIdSelector,
} from '../redux/selectors';

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

function RestaurantsPage({ loadRestaurants, loading, loaded, match }) {
function RestaurantsPage({
loadRestaurants,
loading,
loaded,
match,
firstRestId,
}) {
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>
</>
);
return <Redirect from="/restaurants" to={`/restaurants/${firstRestId}`} />;
}

return <Route path="/restaurants/:restId" component={Restaurants} />;
}

export default connect(
createStructuredSelector({
firstRestId: firstRestaurantIdSelector,
restaurants: restaurantsListSelector,
loading: restaurantsLoadingSelector,
loaded: restaurantsLoadedSelector,
Expand Down
26 changes: 26 additions & 0 deletions src/redux/actions.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import {
DECREMENT,
REMOVE,
ADD_REVIEW,
CHECKOUT,
LOAD_RESTAURANTS,
LOAD_REVIEWS,
LOAD_PRODUCTS,
Expand Down Expand Up @@ -67,3 +68,28 @@ export const loadUsers = () => async (dispatch, getState) => {

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

export const checkout = (checkoutProducts) => async (dispatch, getState) => {
dispatch({ type: CHECKOUT + REQUEST });
try {
const response = await fetch('/api/order', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(checkoutProducts),
}).then(async (res) => {
if (!res.ok) {
const text = await res.json();

throw new Error(text);
} else {
return res.json();
}
});

dispatch({ type: CHECKOUT + SUCCESS, response });
dispatch(replace('/success'));
} catch (error) {
dispatch({ type: CHECKOUT + FAILURE, error: error?.message });
dispatch(replace('/error', { error: error?.message }));
Copy link
Owner

Choose a reason for hiding this comment

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

это состояние лучше все таки хранить в redux

}
};
1 change: 1 addition & 0 deletions src/redux/constants.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ export const INCREMENT = 'INCREMENT';
export const DECREMENT = 'DECREMENT';
export const REMOVE = 'REMOVE';
export const ADD_REVIEW = 'ADD_REVIEW';
export const CHECKOUT = 'CHECKOUT';

export const LOAD_RESTAURANTS = 'LOAD_RESTAURANTS';
export const LOAD_PRODUCTS = 'LOAD_PRODUCTS';
Expand Down
Loading