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

HT4 #41

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

HT4 #41

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
15,940 changes: 15,940 additions & 0 deletions package-lock.json

Large diffs are not rendered by default.

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.2",
"web-vitals": "^0.2.4"
},
"scripts": {
Expand Down
6 changes: 1 addition & 5 deletions src/components/menu/menu.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +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
).isRequired,
menu: PropTypes.arrayOf(PropTypes.string.isRequired).isRequired,
};

state = { error: null };
Expand Down
5 changes: 3 additions & 2 deletions src/components/product/product.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import PropTypes from 'prop-types';
import styles from './product.module.css';

import { decrement, increment } from '../../redux/actions';
import { orderSelector, productsSelector } from '../../redux/selectors';

import Button from '../button';

Expand Down Expand Up @@ -50,8 +51,8 @@ Product.propTypes = {
};

const mapStateToProps = (state, ownProps) => ({
amount: state.order[ownProps.id] || 0,
product: state.products[ownProps.id],
amount: orderSelector(state)[ownProps.id] || 0,
Copy link
Owner

Choose a reason for hiding this comment

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

лучше сразу делать селекторы, которые принимаю и стейт и пропы - orderSelector(state, ownProps) чтобы менять потом в компоненте при изменении структуры данных

product: productsSelector(state)[ownProps.id],
});

// const mapDispatchToProps = {
Expand Down
34 changes: 22 additions & 12 deletions src/components/restaurant/restaurant.js
Original file line number Diff line number Diff line change
@@ -1,22 +1,31 @@
import React, { useMemo } 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 { reviewsSelector, restaurantsSelector } from '../../redux/selectors';

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

const averageRating = useMemo(() => {
const total = reviews.reduce((acc, { rating }) => acc + rating, 0);
const total = reviews.reduce(
Copy link
Owner

Choose a reason for hiding this comment

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

это лучше перенести в селекторы

(acc, id) => acc + restaurantReviews[id].rating,
0
);

return Math.round(total / reviews.length);
}, [reviews]);
}, [reviews, restaurantReviews]);

const tabs = [
{ title: 'Menu', content: <Menu menu={menu} /> },
{ title: 'Reviews', content: <Reviews reviews={reviews} /> },
{
title: 'Reviews',
content: <Reviews reviews={reviews} activeRestaurantId={id} />,
},
];

return (
Expand All @@ -32,13 +41,14 @@ const Restaurant = ({ restaurant }) => {
Restaurant.propTypes = {
restaurant: PropTypes.shape({
name: PropTypes.string,
menu: PropTypes.array,
reviews: PropTypes.arrayOf(
PropTypes.shape({
rating: PropTypes.number.isRequired,
}).isRequired
).isRequired,
menu: PropTypes.arrayOf(PropTypes.string.isRequired).isRequired,
reviews: PropTypes.arrayOf(PropTypes.string.isRequired).isRequired,
}).isRequired,
};

export default Restaurant;
const mapStateToProps = (state, ownProps) => ({
restaurant: restaurantsSelector(state)[ownProps.id],
restaurantReviews: reviewsSelector(state),
});

export default connect(mapStateToProps)(Restaurant);
9 changes: 5 additions & 4 deletions src/components/restaurants/restaurants.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,24 +3,25 @@ import { connect } from 'react-redux';
import PropTypes from 'prop-types';
import Restaurant from '../restaurant';
import Tabs from '../tabs';
import { restaurantsSelector } from '../../redux/selectors';

const Restaurants = ({ restaurants }) => {
const tabs = restaurants.map((restaurant) => ({
const tabs = Object.values(restaurants).map((restaurant) => ({
Copy link
Owner

Choose a reason for hiding this comment

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

Object. values(restaurants) должно быть в селекторах и мемоизировано

title: restaurant.name,
content: <Restaurant restaurant={restaurant} />,
content: <Restaurant id={restaurant.id} />,
}));

return <Tabs tabs={tabs} />;
};

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

export default connect((state) => ({
restaurants: state.restaurants,
restaurants: restaurantsSelector(state),
}))(Restaurants);
7 changes: 4 additions & 3 deletions src/components/reviews/review-form/review-form.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,11 @@ 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: '', rating: 5 };

const ReviewForm = ({ onSubmit }) => {
const ReviewForm = ({ onSubmit, activeRestaurantId }) => {
const { values, handlers, reset } = useForm(INITIAL_VALUES);

const handleSubmit = (ev) => {
Expand Down Expand Up @@ -51,6 +52,6 @@ const ReviewForm = ({ onSubmit }) => {
);
};

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

import Rate from '../../rate';
import styles from './review.module.css';

const Review = ({ user, text, rating }) => (
import { reviewsSelector, usersSelector } from '../../../redux/selectors';

const Review = ({ review, userName }) => (
<div className={styles.review} data-id="review">
<div className={styles.content}>
<div>
<h4 className={styles.name} data-id="review-user">
{user}
{userName.name}
</h4>
<p className={styles.comment} data-id="review-text">
{text}
{review.text}
</p>
</div>
<div className={styles.rate}>
<Rate value={rating} />
<Rate value={review.rating} />
</div>
</div>
</div>
);

Review.propTypes = {
user: PropTypes.string,
text: PropTypes.string,
rating: PropTypes.number.isRequired,
review: PropTypes.shape({
id: PropTypes.string.isRequired,
userId: PropTypes.string,
text: PropTypes.string,
rating: PropTypes.number.isRequired,
}).isRequired,
userName: PropTypes.shape({
id: PropTypes.string.isRequired,
name: PropTypes.string,
}).isRequired,
};

Review.defaultProps = {
user: 'Anonymous',
userName: { name: 'Anonymous' },
};

const mapStateToProps = (state, ownProps) => {
const review = reviewsSelector(state)[ownProps.id];
Copy link
Owner

Choose a reason for hiding this comment

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

все эти вычисления нужно выносить в селекторы, чтобы компонент занимался только рендером

const userId = review.userId;
const userName = usersSelector(state)[userId];

return {
review,
userName,
};
};

export default Review;
export default connect(mapStateToProps, null)(Review);
14 changes: 5 additions & 9 deletions src/components/reviews/reviews.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,23 +4,19 @@ import Review from './review';
import ReviewForm from './review-form';
import styles from './reviews.module.css';

const Reviews = ({ reviews }) => {
const Reviews = ({ reviews, activeRestaurantId }) => {
return (
<div className={styles.reviews}>
{reviews.map((review) => (
<Review key={review.id} {...review} />
{reviews.map((id) => (
<Review key={id} id={id} />
))}
<ReviewForm />
<ReviewForm activeRestaurantId={activeRestaurantId} />
</div>
);
};

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

export default Reviews;
6 changes: 5 additions & 1 deletion src/redux/actions.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
import { INCREMENT, DECREMENT, REMOVE } from './constants';
import { INCREMENT, DECREMENT, REMOVE, ADD_REVIEW } 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 = (values, activeRestaurantId) => ({
type: ADD_REVIEW,
payload: { values, activeRestaurantId },
});
1 change: 1 addition & 0 deletions src/redux/constants.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
export const INCREMENT = 'INCREMENT';
export const DECREMENT = 'DECREMENT';
export const REMOVE = 'REMOVE';
export const ADD_REVIEW = 'ADD_REVIEW';
16 changes: 16 additions & 0 deletions src/redux/middleware/uuidCreator.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import { v4 as uuidv4 } from 'uuid';

export default (state) => (next) => (action) => {
if (action.type === 'ADD_REVIEW') {
const newReviewId = uuidv4();
const newUserId = uuidv4();

action.payload.values = {
Copy link
Owner

Choose a reason for hiding this comment

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

не стоит мутировать action, лучше создать новый

id: newReviewId,
userId: newUserId,
...action.payload.values,
};
}

next(action);
};
2 changes: 2 additions & 0 deletions src/redux/reducer/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,12 @@ import order from './order';
import restaurants from './restaurants';
import products from './products';
import reviews from './reviews';
import users from './users';

export default combineReducers({
order,
restaurants,
products,
reviews,
users,
});
26 changes: 24 additions & 2 deletions src/redux/reducer/restaurants.js
Original file line number Diff line number Diff line change
@@ -1,9 +1,31 @@
import { normalizedRestaurants as defaultRestaurants } from '../../fixtures';
import { normalizedRestaurants } from '../../fixtures';
import { ADD_REVIEW } from '../constants';

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

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

switch (type) {
case ADD_REVIEW: {
const addedNewReview = payload.values.id;
const activeRestaurantId = payload.activeRestaurantId.activeRestaurantId;
const activeRestaurantData = restaurants[activeRestaurantId];

return {
...restaurants,
[activeRestaurantId]: {
...activeRestaurantData,
...activeRestaurantData.reviews.push(addedNewReview),
Copy link
Owner

Choose a reason for hiding this comment

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

это все равно мутация reviews по ссылке, такого делать нельзя

},
};
}
default:
return restaurants;
}
Expand Down
18 changes: 16 additions & 2 deletions src/redux/reducer/reviews.js
Original file line number Diff line number Diff line change
@@ -1,9 +1,23 @@
import { normalizedReviews as defaultReviews } from '../../fixtures';
import { normalizedReviews } from '../../fixtures';
import { ADD_REVIEW } from '../constants';

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

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

switch (type) {
case ADD_REVIEW:
const newReview = { ...payload.values };
delete newReview.name;

return {
...reviews,
[newReview.id]: newReview,
};
default:
return reviews;
}
Expand Down
28 changes: 28 additions & 0 deletions src/redux/reducer/users.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import { normalizedUsers } from '../../fixtures';
import { ADD_REVIEW } from '../constants';

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

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

switch (type) {
case ADD_REVIEW: {
const newUserId = payload.values.userId;
const newUserName = payload.values.name;

return {
...users,
[newUserId]: {
id: newUserId,
name: newUserName,
},
};
}
default:
return users;
}
};
8 changes: 5 additions & 3 deletions src/redux/selectors.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
import { createSelector } from 'reselect';

// const restaurantsSelector = (state) => state.restaurants;
const orderSelector = (state) => state.order;
const productsSelector = (state) => state.products;
export const restaurantsSelector = (state) => state.restaurants;
export const orderSelector = (state) => state.order;
export const productsSelector = (state) => state.products;
export const reviewsSelector = (state) => state.reviews;
export const usersSelector = (state) => state.users;

export const orderProductsSelector = createSelector(
productsSelector,
Expand Down
Loading