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

Ht7 #57

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open

Ht7 #57

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
6 changes: 3 additions & 3 deletions src/components/app/app.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import React, { useState } from 'react';
import { Route, Switch } from 'react-router-dom';
import { Route, Switch, Redirect } from 'react-router-dom';
import RestaurantsPage from '../../pages/restaurants-page';
import Header from '../header';
import Basket from '../basket';
Expand All @@ -13,10 +13,10 @@ const App = () => {
<UserProvider value={{ name, setName }}>
<Header />
<Switch>
<Route path="/checkout" component={Basket} />
<Route path="/checkout" exact component={Basket} />
<Route path="/restaurants" component={RestaurantsPage} />
<Route path="/error" component={() => <h1>Error Page</h1>} />
<Route path="/" component={() => '404 - Not found'} />
<Redirect exact from="/" to={`/restaurants/`} />
</Switch>
</UserProvider>
</div>
Expand Down
63 changes: 52 additions & 11 deletions src/components/basket/basket.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import React from 'react';
import React, { useMemo } from 'react';
import { connect } from 'react-redux';
import { Link } from 'react-router-dom';
import { Link, withRouter } from 'react-router-dom';
import { createStructuredSelector } from 'reselect';
import { CSSTransition, TransitionGroup } from 'react-transition-group';

Expand All @@ -10,11 +10,49 @@ import styles from './basket.module.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 {
orderProductsSelector,
totalSelector,
locationSelector,
orderLoadingSelector,
errorOrderSelector,
successOrderSelector,
} from '../../redux/selectors';
import { UserConsumer } from '../../contexts/user-context';
import { takeOrder } from '../../redux/actions';
import LoadBanner from '../loadBanner';

function Basket({ title = 'Basket', total, orderProducts }) {
function Basket({
title = 'Basket',
total,
orderProducts,
loading,
location,
history,
takeOrder,
errorOrder,
successOrderMessage,
}) {
// const { name } = useContext(userContext);
const canTakeOrder = useMemo(() => {
return location.pathname === '/checkout';
}, [location]);

function onBtnHandler() {
if (canTakeOrder) {
takeOrder();
} else {
history.push('/checkout');
}
}

if (successOrderMessage) {
return (
<div className={styles.basket}>
<h4 className={styles.title}>{successOrderMessage}</h4>
</div>
);
}

if (!total) {
return (
Expand All @@ -26,7 +64,7 @@ function Basket({ title = 'Basket', total, orderProducts }) {

return (
<div className={styles.basket}>
{/* <h4 className={styles.title}>{`${name}'s ${title}`}</h4> */}
{loading && <LoadBanner />}
<h4 className={styles.title}>
<UserConsumer>{({ name }) => `${name}'s ${title}`}</UserConsumer>
</h4>
Expand Down Expand Up @@ -55,18 +93,21 @@ function Basket({ title = 'Basket', total, orderProducts }) {
<p>{`${total} $`}</p>
</div>
</div>
<Link to="/checkout">
<Button primary block>
checkout
</Button>
</Link>
<div>{errorOrder}</div>
<Button primary block onClick={onBtnHandler}>
checkout
</Button>
</div>
);
}

const mapStateToProps = createStructuredSelector({
total: totalSelector,
orderProducts: orderProductsSelector,
location: locationSelector,
loading: orderLoadingSelector,
errorOrder: errorOrderSelector,
successOrderMessage: successOrderSelector,
});

export default connect(mapStateToProps)(Basket);
export default connect(mapStateToProps, { takeOrder })(withRouter(Basket));
1 change: 1 addition & 0 deletions src/components/loadBanner/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export { default } from './loadBanner';
13 changes: 13 additions & 0 deletions src/components/loadBanner/loadBanner.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import React from 'react';
import Loader from '../loader';
import styles from './loadBanner.module.css';

function LoadBanner() {
return (
<div className={styles.loadBanner}>
<Loader />
</div>
);
}

export default LoadBanner;
10 changes: 10 additions & 0 deletions src/components/loadBanner/loadBanner.module.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
.loadBanner {
position: absolute;
width: 100%;
height: 100%;
top: 0;
left: 0;
display: flex;
align-items: center;
background: rgb(0 0 0 / 18%);
}
25 changes: 15 additions & 10 deletions src/pages/restaurants-page.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import React, { useEffect } from 'react';
import React, { useEffect, useMemo } from 'react';
import { connect } from 'react-redux';
import { Route } from 'react-router-dom';
import { Route, Redirect } from 'react-router-dom';
import { createStructuredSelector } from 'reselect';
import Restaurants from '../components/restaurants';
import Loader from '../components/loader';
Expand All @@ -12,20 +12,25 @@ import {
} from '../redux/selectors';
import { loadRestaurants } from '../redux/actions';

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

const firstRestaurantId = useMemo(() => {
return restaurants.length ? restaurants[0].id : null;
}, [restaurants]);

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

if (match.isExact) {
return (
<>
<Restaurants match={match} />
<h2 style={{ textAlign: 'center' }}>Select restaurant</h2>
</>
);
if (match.isExact && firstRestaurantId) {
return <Redirect to={`/restaurants/${firstRestaurantId}`} />;
}

return <Route path="/restaurants/:restId" component={Restaurants} />;
Expand Down
50 changes: 50 additions & 0 deletions src/redux/actions.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,18 @@ import {
LOAD_REVIEWS,
LOAD_PRODUCTS,
LOAD_USERS,
ORDER_SUCCESS,
ORDER_ERROR,
ORDER_LOADING_TOGGLE,
CLEAN_OUT,
} from './constants';
import products from './reducer/products';
import {
usersLoadingSelector,
usersLoadedSelector,
reviewsLoadingSelector,
reviewsLoadedSelector,
orderSelector,
} from './selectors';

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

dispatch(_loadUsers());
};

export const takeOrder = () => async (dispatch, getState) => {
const state = orderSelector(getState());
const order = Object.keys(state).map((productId) => {
Copy link
Owner

Choose a reason for hiding this comment

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

используйте селекторы

return { id: productId, amount: state[productId] };
});

dispatch(orderLoading(true));
Copy link
Owner

Choose a reason for hiding this comment

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

лучше делать такого же вида екшены, как и на загрузку данных (через REQUEST, SUCCESS, FAILURE) - тогда все будет в едином стиле и проще для понимания

Copy link
Author

Choose a reason for hiding this comment

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

Я не очень поняла, как через REQUEST, SUCCESS, FAILURE это работает и зачем два значения в state, если можно ввести одно значение для определения,, что идет загрузка.


await fetch('/api/order', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(order),
})
.then((res) => {
return res.json();
})
.then((res) => {
dispatch(orderLoading(false));
if (res === 'ok') {
dispatch(orderSuccess());

return;
}

dispatch(orderError(res));
})
.catch(dispatch(orderError));
};

const orderSuccess = () => ({
type: CLEAN_OUT,
payload: {},
});

const orderLoading = (isLoad) => ({
type: ORDER_LOADING_TOGGLE,
payload: { loading: isLoad },
});

const orderError = (error) => ({
type: ORDER_ERROR,
payload: { error },
});
4 changes: 4 additions & 0 deletions src/redux/constants.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,3 +11,7 @@ export const LOAD_USERS = 'LOAD_USERS';
export const REQUEST = '_REQUEST';
export const SUCCESS = '_SUCCESS';
export const FAILURE = '_FAILURE';

export const ORDER_ERROR = 'ORDER_ERROR';
export const ORDER_LOADING_TOGGLE = 'ORDER_LOADING_TOGGLE';
export const CLEAN_OUT = 'CLEAN_OUT';
57 changes: 51 additions & 6 deletions src/redux/reducer/order.js
Original file line number Diff line number Diff line change
@@ -1,20 +1,65 @@
import { DECREMENT, INCREMENT, REMOVE } from '../constants';
import {
DECREMENT,
INCREMENT,
REMOVE,
ORDER_LOADING_TOGGLE,
ORDER_ERROR,
CLEAN_OUT,
} from '../constants';

// { [productId]: amount }
export default (state = {}, action) => {
const { type, payload } = action;

const initialState = {
entities: {},
loading: false,
error: null,
success: null,
// payload: 0,
};

export default (state = initialState, action) => {
const { type, payload, loading } = action;
switch (type) {
case INCREMENT:
return { ...state, [payload.id]: (state[payload.id] || 0) + 1 };
return {
...state,
entities: {
...state.entities,
[payload.id]: (state.entities[payload.id] || 0) + 1,
},
};
case DECREMENT:
return {
...state,
[payload.id]: Math.max((state[payload.id] || 0) - 1, 0),
entities: {
...state.entities,
[payload.id]: Math.max((state.entities[payload.id] || 0) - 1, 0),
},
};
case REMOVE:
return {
...state,
[payload.id]: 0,
entities: {
...state.entities,
[payload.id]: 0,
},
};
case ORDER_LOADING_TOGGLE:
return {
...state,
loading: payload.loading,
};
case ORDER_ERROR:
return {
...state,
error: payload.error,
};
case CLEAN_OUT:
return {
...state,
entities: {},
success: 'Заказ сформирован',
error: null,
};
default:
return state;
Expand Down
12 changes: 11 additions & 1 deletion src/redux/selectors.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,20 @@ import { createSelector } from 'reselect';
import { getById } from './utils';

const restaurantsSelector = (state) => state.restaurants.entities;
const orderSelector = (state) => state.order;
export const orderSelector = (state) => state.order.entities;
const productsSelector = (state) => state.products.entities;
const reviewsSelector = (state) => state.reviews.entities;
const usersSelector = (state) => state.users.entities;
const historyRouterSelector = (state) => state.router;
Copy link
Owner

Choose a reason for hiding this comment

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

в connected-react-router есть свои селекторы, которые можно так же использовать


export const orderLoadingSelector = (state) => state.order.loading;
export const errorOrderSelector = (state) => state.order.error;
export const successOrderSelector = (state) => state.order.success;

export const locationSelector = createSelector(
historyRouterSelector,
(history) => history.location
);

export const restaurantsLoadingSelector = (state) => state.restaurants.loading;
export const restaurantsLoadedSelector = (state) => state.restaurants.loaded;
Expand Down