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

Lesson6 #84

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: 2 additions & 2 deletions src/components/app/app.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { PureComponent } from 'react';
import { Route, Switch } from 'react-router-dom';
import { Route, Switch, Redirect } from 'react-router-dom';
import Restaurants from '../restaurants';
import Header from '../header';
import Basket from '../basket';
Expand All @@ -10,9 +10,9 @@ export default class App extends PureComponent {
<div>
<Header />
<Switch>
<Route path="/" exact component={() => <h2>Home page</h2>} />
<Route path="/checkout" component={Basket} />
<Route path="/restaurants" component={Restaurants} />
<Redirect from="/" exact to={'/restaurants'} />
<Route component={() => <h2>404 - Not found :(</h2>} />
</Switch>
</div>
Expand Down
5 changes: 4 additions & 1 deletion src/components/basket/basket-item/basket-item.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { connect } from 'react-redux';
import { Link } from 'react-router-dom';
import cn from 'classnames';
import { increment, decrement, remove } from '../../../redux/actions';
import Button from '../../button';
Expand All @@ -15,7 +16,9 @@ function BasketItem({
return (
<div className={styles.basketItem}>
<div className={styles.name}>
<span>{product.name}</span>
<Link to={`/restaurants/${product.restId}/menu`}>
<span>{product.name}</span>
</Link>
</div>
<div className={styles.info}>
<div className={styles.counter}>
Expand Down
12 changes: 9 additions & 3 deletions src/components/header/header.js
Original file line number Diff line number Diff line change
@@ -1,13 +1,19 @@
import { connect } from 'react-redux';
import { Link } from 'react-router-dom';
import { ReactComponent as Logo } from '../../icons/logo.svg';
import styles from './header.module.css';
import { changeActiveRestaurantTab } from '../../redux/actions';

const Header = () => (
const Header = ({ changeActiveRestaurantTab }) => (
<header className={styles.header}>
<Link to="/restaurants">
<Link to="/restaurants" onClick={() => changeActiveRestaurantTab('menu')}>
<Logo />
</Link>
</header>
);

export default Header;
const mapDispatchToProps = {
changeActiveRestaurantTab,
};

export default connect(null, mapDispatchToProps)(Header);
51 changes: 42 additions & 9 deletions src/components/restaurant/restaurant.js
Original file line number Diff line number Diff line change
@@ -1,21 +1,28 @@
import { useState } from 'react';
import { connect } from 'react-redux';
import { NavLink, Switch, Redirect, Route } from 'react-router-dom';
import PropTypes from 'prop-types';
import Menu from '../menu';
import Reviews from '../reviews';
import Banner from '../banner';
import Rate from '../rate';
import Tabs from '../tabs';
import {
averageRatingSelector,
restaurantSelector,
} from '../../redux/selectors';
import {
changeActiveRestaurantTab,
getActiveRestaurantTab,
} from '../../redux/actions';
import styles from './restaurant.module.css';

const Restaurant = ({ restaurant, averageRating }) => {
const Restaurant = ({
restaurant,
averageRating,
changeActiveRestaurantTab,
getActiveRestaurantTab,
}) => {
const { id, name, menu, reviews } = restaurant;

const [activeTab, setActiveTab] = useState('menu');

const tabs = [
{ id: 'menu', label: 'Menu' },
{ id: 'reviews', label: 'Reviews' },
Expand All @@ -26,9 +33,30 @@ const Restaurant = ({ restaurant, averageRating }) => {
<Banner heading={name}>
<Rate value={averageRating} />
</Banner>
<Tabs tabs={tabs} activeId={activeTab} onChange={setActiveTab} />
{activeTab === 'menu' && <Menu menu={menu} key={id} restId={id} />}
{activeTab === 'reviews' && <Reviews reviews={reviews} restId={id} />}
<div className={styles.tabs}>
{tabs.map(({ id: tabID, label }) => (
<NavLink
key={tabID}
to={`/restaurants/${id}/${tabID}`}
className={styles.tab}
activeClassName={styles.active}
onClick={() => changeActiveRestaurantTab(tabID)}
>
{label}
</NavLink>
))}
</div>
<Switch>
<Route
path="/restaurants/:restId/menu"
component={() => <Menu menu={menu} key={id} restId={id} />}
/>
<Route
path="/restaurants/:restId/reviews"
component={() => <Reviews reviews={reviews} restId={id} />}
/>
<Redirect to={`/restaurants/:restId/${getActiveRestaurantTab()}`} />;
Copy link
Owner

Choose a reason for hiding this comment

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

тут нужно просто редиректить на меню

Copy link
Author

Choose a reason for hiding this comment

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

Вот собственно ради этого все и затевалось :)
если по умолчанию редиректить на меню, у нас относительно текущей версии приложения потеряется сохранение выбранной подвкладки ресторана. А менять эту логику не хотелось.

</Switch>
</div>
);
};
Expand All @@ -43,9 +71,14 @@ Restaurant.propTypes = {
averageRating: PropTypes.number,
};

const mapDispatchToProps = {
changeActiveRestaurantTab,
getActiveRestaurantTab,
};

const mapStateToProps = (state, props) => ({
restaurant: restaurantSelector(state, props),
averageRating: averageRatingSelector(state, props),
});

export default connect(mapStateToProps)(Restaurant);
export default connect(mapStateToProps, mapDispatchToProps)(Restaurant);
19 changes: 19 additions & 0 deletions src/components/restaurant/restaurant.module.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
.tabs {
height: auto;
text-align: center;
padding: 12px;
background-color: var(--grey);
}

.tabs span {
cursor: pointer;
}

.tab {
padding: 4px 12px;
color: var(--black);
}

.tab.active {
border-bottom: 1px solid var(--black);
}
14 changes: 14 additions & 0 deletions src/redux/actions.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,13 +11,15 @@ import {
REQUEST,
SUCCESS,
FAILURE,
CHANGE_RESTAURANT_TAB,
} from './constants';

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

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

dispatch(_loadUsers());
};

export const changeActiveRestaurantTab = (tab) => {
return {
type: CHANGE_RESTAURANT_TAB,
restaurantActiveTab: tab,
};
};

export const getActiveRestaurantTab = () => (_dispatch, getState) => {
Copy link
Owner

Choose a reason for hiding this comment

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

это не экшен, а селетор.

Copy link
Author

Choose a reason for hiding this comment

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

Тут собственно так сделано, чтобы получить значение однократно при перерендере компоненты с новым рестораном, а не при каждой смене таба. Не очень понимаю, как можно для этого использовать селектор, можно подробнее?

const state = getState();
return activeTabSelector(state);
};
1 change: 1 addition & 0 deletions src/redux/constants.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ export const REMOVE = 'REMOVE';
export const ADD_REVIEW = 'ADD_REVIEW';

export const CHANGE_RESTAURANT = 'CHANGE_RESTAURANT';
export const CHANGE_RESTAURANT_TAB = 'CHANGE_RESTAURANT_TAB';

export const LOAD_RESTAURANTS = 'LOAD_RESTAURANTS';
export const LOAD_PRODUCTS = 'LOAD_PRODUCTS';
Expand Down
2 changes: 2 additions & 0 deletions src/redux/reducer/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,13 @@ import restaurants from './restaurants';
import products from './products';
import reviews from './reviews';
import users from './users';
import sessionParam from './session-param';

export default combineReducers({
order,
restaurants,
products,
reviews,
users,
sessionParam,
});
3 changes: 2 additions & 1 deletion src/redux/reducer/products.js
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,8 @@ export default (state = initialState, action) =>
draft.loading[restId] = false;
draft.loaded[restId] = true;
draft.error = null;
Object.assign(draft.entities, arrToMap(data));
const dataWithRestId = data.map((obj) => ({ ...obj, restId }));
Object.assign(draft.entities, arrToMap(dataWithRestId));
Copy link
Owner

Choose a reason for hiding this comment

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

Из данных, которые у нас лежат в редьюсере ресторанов мы можем однозначно сказать какой продукт из какого ресторана. Теперь эта информация у нас есть в двух местах, тут и в ресторанах. Так делать не стоит.

Copy link
Author

Choose a reason for hiding this comment

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

Вот про это очень интересно, мне казалось, что обратные ссылки это нормально :))

break;
}
case LOAD_PRODUCTS + FAILURE: {
Expand Down
14 changes: 14 additions & 0 deletions src/redux/reducer/session-param.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import produce from 'immer';
import { CHANGE_RESTAURANT_TAB } from '../constants';

export default produce((draft = { restaurantActiveTab: 'menu' }, action) => {
Copy link
Owner

Choose a reason for hiding this comment

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

у нас эта вкладка есть в роутинге, не совсем понимаю зачем ее сохранять в редакс

Copy link
Author

Choose a reason for hiding this comment

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

Хотелось сохранить логику, чтобы при переключении ресторана не менялась выбраная подвкладка и при этом не хотелось показывать эту подвкладку родительским компонентам.
Как при переключении по Navlink получить предыдущую вкладку не придумалось, пришлось сохранять в редакс.

const { type, restaurantActiveTab } = action;

switch (type) {
case CHANGE_RESTAURANT_TAB:
draft.restaurantActiveTab = restaurantActiveTab;
break;
default:
return draft;
}
});
4 changes: 4 additions & 0 deletions src/redux/selectors.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ const productsSelector = (state) => state.products.entities;
const orderSelector = (state) => state.order;
const reviewsSelector = (state) => state.reviews.entities;
const usersSelector = (state) => state.users.entities;
const sessionParamSelector = (state) => state.sessionParam;

export const activeIdRestaurantSelector = (state) => state.restaurants.activeId;
export const restaurantsLoadingSelector = (state) => state.restaurants.loading;
Expand Down Expand Up @@ -72,3 +73,6 @@ export const averageRatingSelector = createSelector(
);
}
);

export const activeTabSelector = (state) =>
sessionParamSelector(state).restaurantActiveTab;