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-4: fix reviews & post new review #64

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 package.json
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
"redux": "^4.0.5",
"redux-devtools-extension": "^2.13.8",
"reselect": "^4.0.0",
"uuid": "^8.3.1",
"web-vitals": "^0.2.4"
},
"scripts": {
Expand Down
4 changes: 1 addition & 3 deletions src/components/menu/menu.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,7 @@ import styles from './menu.module.css';
class Menu extends React.Component {
static propTypes = {
menu: PropTypes.arrayOf(
PropTypes.shape({
id: PropTypes.string.isRequired,
}).isRequired
PropTypes.string.isRequired
).isRequired,
};

Expand Down
25 changes: 14 additions & 11 deletions src/components/restaurant/restaurant.js
Original file line number Diff line number Diff line change
@@ -1,19 +1,16 @@
import React, { useMemo } from 'react';
import React from 'react';
import { connect } from 'react-redux';
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 { makeRatingSelector } from '../../redux/selectors';

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

const averageRating = useMemo(() => {
const total = reviews.reduce((acc, { rating }) => acc + rating, 0);
return Math.round(total / reviews.length);
}, [reviews]);

const tabs = [
{ title: 'Menu', content: <Menu menu={menu} /> },
{ title: 'Reviews', content: <Reviews reviews={reviews} /> },
Expand All @@ -34,11 +31,17 @@ Restaurant.propTypes = {
name: PropTypes.string,
menu: PropTypes.array,
reviews: PropTypes.arrayOf(
PropTypes.shape({
rating: PropTypes.number.isRequired,
}).isRequired
PropTypes.string.isRequired
).isRequired,
}).isRequired,
};

export default Restaurant;
const mapStateToProps = () => {
const ratingSelector = makeRatingSelector();

return (state, ownProps) => ({
averageRating: ratingSelector(state, ownProps.restaurant.id)
});
};

export default connect(mapStateToProps)(Restaurant);
21 changes: 16 additions & 5 deletions src/components/restaurants/restaurants.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,19 @@ import { connect } from 'react-redux';
import PropTypes from 'prop-types';
import Restaurant from '../restaurant';
import Tabs from '../tabs';
import {restaurantListSelector} from '../../redux/selectors';
import {selectRestaurant} from '../../redux/actions';

const Restaurants = ({ restaurants }) => {
const Restaurants = ({ restaurants, activeRestaurant, selectRestaurant }) => {
const tabs = restaurants.map((restaurant) => ({
title: restaurant.name,
content: <Restaurant restaurant={restaurant} />,
}));

return <Tabs tabs={tabs} />;
const changeTab = (index) => selectRestaurant(restaurants[index].id);
const initialActiveTab = restaurants.findIndex(restaurant => activeRestaurant === restaurant.id);

return <Tabs tabs={tabs} initialActiveTab={initialActiveTab} onChange={changeTab} />;
};

Restaurants.propTypes = {
Expand All @@ -21,6 +26,12 @@ Restaurants.propTypes = {
).isRequired,
};

export default connect((state) => ({
restaurants: state.restaurants,
}))(Restaurants);
export default connect(
(state) => ({
restaurants: restaurantListSelector(state),
activeRestaurant: state.activeRestaurant
}),
(dispatch) => ({
selectRestaurant: id => dispatch(selectRestaurant(id))
})
)(Restaurants);
9 changes: 5 additions & 4 deletions src/components/reviews/review-form/review-form.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,9 @@ import Rate from '../../rate';
import styles from './review-form.module.css';
import { connect } from 'react-redux';
import Button from '../../button';
import { addReview } from "../../../redux/actions";

const INITIAL_VALUES = { name: '', text: '', rate: 5 };
const INITIAL_VALUES = { name: '', text: '', rating: 5 };

const ReviewForm = ({ onSubmit }) => {
const { values, handlers, reset } = useForm(INITIAL_VALUES);
Expand Down Expand Up @@ -38,7 +39,7 @@ const ReviewForm = ({ onSubmit }) => {
<div className={styles.rateWrap}>
<span>Rating: </span>
<span>
<Rate {...handlers.rate} />
<Rate {...handlers.rating} />
</span>
</div>
<div className={styles.publish}>
Expand All @@ -51,6 +52,6 @@ const ReviewForm = ({ onSubmit }) => {
);
};

export default connect(null, () => ({
onSubmit: (values) => console.log(values), // TODO
export default connect(null, (dispatch) => ({
onSubmit: (values) => dispatch(addReview(values))
}))(ReviewForm);
13 changes: 12 additions & 1 deletion src/components/reviews/review/review.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import React from 'react';
import { connect } from 'react-redux';
import PropTypes from 'prop-types';

import Rate from '../../rate';
Expand Down Expand Up @@ -32,4 +33,14 @@ Review.defaultProps = {
user: 'Anonymous',
};

export default Review;
const mapStateToProps = (state, ownProps) => {
const review = state.reviews[ownProps.id];

return {
user: state.users[review?.userId]?.name,
Copy link
Owner

Choose a reason for hiding this comment

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

это нужно выносить в селекторы

text: review?.text,
rating: review?.rating
}
};

export default connect(mapStateToProps)(Review);
8 changes: 3 additions & 5 deletions src/components/reviews/reviews.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,8 @@ import styles from './reviews.module.css';
const Reviews = ({ reviews }) => {
return (
<div className={styles.reviews}>
{reviews.map((review) => (
<Review key={review.id} {...review} />
{reviews.map((id) => (
<Review key={id} id={id} />
))}
<ReviewForm />
</div>
Expand All @@ -17,9 +17,7 @@ const Reviews = ({ reviews }) => {

Reviews.propTypes = {
reviews: PropTypes.arrayOf(
PropTypes.shape({
id: PropTypes.string.isRequired,
}).isRequired
PropTypes.string.isRequired
).isRequired,
};

Expand Down
11 changes: 8 additions & 3 deletions src/components/tabs/tabs.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,19 +4,24 @@ import cn from 'classnames';

import styles from './tabs.module.css';

const Tabs = ({ tabs }) => {
const [activeTab, setActiveTab] = useState(0);
const Tabs = ({ tabs, initialActiveTab = 0, onChange }) => {
const [activeTab, setActiveTab] = useState(initialActiveTab);

const { content } = tabs[activeTab];

const activateTab = (index) => {
setActiveTab(index);
onChange && onChange(index);
};

return (
<>
<div className={styles.tabs}>
{tabs.map(({ title }, index) => (
<span
key={title}
className={cn(styles.tab, { [styles.active]: index === activeTab })}
onClick={() => setActiveTab(index)}
onClick={() => activateTab(index)}
>
{title}
</span>
Expand Down
4 changes: 3 additions & 1 deletion src/redux/actions.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import { INCREMENT, DECREMENT, REMOVE } from './constants';
import { INCREMENT, DECREMENT, REMOVE, REVIEW_ADD, RESTAURANT_ACTIVATE } from './constants';

export const increment = (id) => ({ type: INCREMENT, payload: { id } });
export const decrement = (id) => ({ type: DECREMENT, payload: { id } });
export const remove = (id) => ({ type: REMOVE, payload: { id } });
export const addReview = (review) => ({ type: REVIEW_ADD, payload: review });
export const selectRestaurant = (id) => ({ type: RESTAURANT_ACTIVATE, payload: { id } });
3 changes: 3 additions & 0 deletions src/redux/constants.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
export const INCREMENT = 'INCREMENT';
export const DECREMENT = 'DECREMENT';
export const REMOVE = 'REMOVE';

export const RESTAURANT_ACTIVATE = 'RESTAURANT_ACTIVATE';
export const REVIEW_ADD = 'REVIEW_ADD';
22 changes: 22 additions & 0 deletions src/redux/middleware/review.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import { v4 as uuidv4 } from 'uuid';
import { REVIEW_ADD } from '../constants';

const review = (store) => (next) => (action) => {
const { type, payload } = action;

if (type === REVIEW_ADD) {
next({
type: type,
payload: {
restaurantId: store.getState().activeRestaurant,
userId: uuidv4(),
id: uuidv4(),
...payload
}
});
} else {
next(action);
}
};

export default review;
17 changes: 17 additions & 0 deletions src/redux/reducer/activeRestaurant.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import { normalizedRestaurants } from '../../fixtures';
import { RESTAURANT_ACTIVATE } from '../constants';

const defaultActiveRestaurant = normalizedRestaurants[0]?.id;

const reducer = (activeRestaurant = defaultActiveRestaurant, action) => {
const { type, payload } = action;

switch (type) {
case RESTAURANT_ACTIVATE:
return payload.id;
default:
return activeRestaurant;
Copy link
Owner

Choose a reason for hiding this comment

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

теперь знание о том, какой ресторан активный, храниться в двух местах - в этом редьюсере и в компоненте

}
};

export default reducer;
4 changes: 4 additions & 0 deletions src/redux/reducer/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,16 @@ import order from './order';
import restaurants from './restaurants';
import products from './products';
import reviews from './reviews';
import users from './users';
import activeRestaurant from './activeRestaurant';

const reducer = combineReducers({
order,
restaurants,
products,
reviews,
users,
activeRestaurant
});

export default reducer;
18 changes: 16 additions & 2 deletions src/redux/reducer/restaurants.js
Original file line number Diff line number Diff line change
@@ -1,9 +1,23 @@
import { normalizedRestaurants as defaultRestaurants } from '../../fixtures';
import { normalizedRestaurants } from '../../fixtures';
import { REVIEW_ADD } from '../constants';

const defaultRestaurants = normalizedRestaurants.reduce(
(acc, restaurant) => ({...acc, [restaurant.id]: restaurant}),
{});

const reducer = (restaurants = defaultRestaurants, action) => {
const { type } = action;
const { type, payload } = action;

switch (type) {
case REVIEW_ADD:
const restaurant = restaurants[payload.restaurantId];
return {
...restaurants,
[restaurant.id]: {
...restaurant,
reviews: [payload.id, ...restaurant.reviews]
}
};
default:
return restaurants;
}
Expand Down
19 changes: 17 additions & 2 deletions src/redux/reducer/reviews.js
Original file line number Diff line number Diff line change
@@ -1,9 +1,24 @@
import { normalizedReviews as defaultReviews } from '../../fixtures';
import { normalizedReviews } from '../../fixtures';
import { REVIEW_ADD } from '../constants';

const defaultReviews = normalizedReviews.reduce(
(acc, review) => ({...acc, [review.id]: review}),
{});

const reducer = (reviews = defaultReviews, action) => {
const { type } = action;
const { type, payload } = action;

switch (type) {
case REVIEW_ADD:
return {
...reviews,
[payload.id]: {
id: payload.id,
userId: payload.userId,
text: payload.text,
rating: payload.rating
}
};
default:
return reviews;
}
Expand Down
25 changes: 25 additions & 0 deletions src/redux/reducer/users.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import { normalizedUsers } from '../../fixtures';
import { REVIEW_ADD } from '../constants';

const defaultUsers = normalizedUsers.reduce(
(acc, user) => ({...acc, [user.id]: user}),
{});

const reducer = (users = defaultUsers, action) => {
const { type, payload } = action;

switch (type) {
case REVIEW_ADD:
return {
...users,
[payload.userId]: {
id: payload.userId,
name: payload.name
}
};
default:
return users;
}
};

export default reducer;
21 changes: 20 additions & 1 deletion src/redux/selectors.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,15 @@
import { createSelector } from 'reselect';

// const restaurantsSelector = (state) => state.restaurants;
const restaurantsSelector = (state) => state.restaurants;
const orderSelector = (state) => state.order;
const productsSelector = (state) => state.products;
const reviewsSelector = (state) => state.reviews;
const restaurantReviewsSelector = (state, restaurantId) => state.restaurants[restaurantId].reviews;

export const restaurantListSelector = createSelector(
restaurantsSelector,
restaurants => Object.keys(restaurants).map(id => restaurants[id])
);

export const orderProductsSelector = createSelector(
productsSelector,
Expand All @@ -24,3 +31,15 @@ export const totalSelector = createSelector(
(orderProducts) =>
orderProducts.reduce((acc, { subtotal }) => acc + subtotal, 0)
);

export const makeRatingSelector = () => createSelector(
Copy link
Owner

@koretskiyav koretskiyav Dec 1, 2020

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.

на случай, если он будет использоваться несколькими компонентами https://github.com/reduxjs/reselect#sharing-selectors-with-props-across-multiple-component-instances

reviewsSelector,
restaurantReviewsSelector,
(reviews, restaurantReviews) => {
const total = restaurantReviews
.map(id => reviews[id])
.reduce((acc, { rating }) => acc + rating, 0);

return Math.round(total / restaurantReviews.length);
}
);
Loading