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 #42

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open

HT4 #42

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: 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.array.isRequired,
};

state = { error: null };
Expand Down
37 changes: 17 additions & 20 deletions src/components/restaurant/restaurant.js
Original file line number Diff line number Diff line change
@@ -1,22 +1,20 @@
import React, { useMemo } from 'react';
import React from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import Menu from '../menu';
import Reviews from '../reviews';
import Banner from '../banner';
import Rate from '../rate';
import Tabs from '../tabs';
import { averageRatingSelector } from '../../redux/selectors';

const Restaurant = ({ restaurant }) => {
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 Restaurant = ({ name, menu, reviews, averageRating, id }) => {
const tabs = [
{ title: 'Menu', content: <Menu menu={menu} /> },
{ title: 'Reviews', content: <Reviews reviews={reviews} /> },
{
title: 'Reviews',
content: <Reviews restaurantId={id} reviews={reviews} />,
},
];

return (
Expand All @@ -30,15 +28,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,
}).isRequired,
name: PropTypes.string,
menu: PropTypes.array.isRequired,
reviews: PropTypes.array.isRequired,
};

export default Restaurant;
export default connect((state, ownProps) => ({
name: state.restaurants[ownProps.id].name,
Copy link
Owner

Choose a reason for hiding this comment

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

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

menu: state.restaurants[ownProps.id].menu,
reviews: state.restaurants[ownProps.id].reviews,
averageRating: averageRatingSelector(state, ownProps),
}))(Restaurant);
12 changes: 4 additions & 8 deletions src/components/restaurants/restaurants.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,20 +5,16 @@ import Restaurant from '../restaurant';
import Tabs from '../tabs';

const Restaurants = ({ restaurants }) => {
const tabs = restaurants.map((restaurant) => ({
title: restaurant.name,
content: <Restaurant restaurant={restaurant} />,
const tabs = Object.keys(restaurants).map((id) => ({
Copy link
Owner

Choose a reason for hiding this comment

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

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

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

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

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

export default connect((state) => ({
Expand Down
10 changes: 6 additions & 4 deletions src/components/reviews/review-form/review-form.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,14 +6,16 @@ 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, restaurantId }) => {
const { values, handlers, reset } = useForm(INITIAL_VALUES);

const handleSubmit = (ev) => {
ev.preventDefault();
onSubmit(values);
onSubmit({ ...values, restaurantId: restaurantId });
reset();
};

Expand Down Expand Up @@ -51,6 +53,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);
12 changes: 9 additions & 3 deletions src/components/reviews/review/review.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import React from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';

import Rate from '../../rate';
import styles from './review.module.css';
Expand Down Expand Up @@ -28,8 +29,13 @@ Review.propTypes = {
rating: PropTypes.number.isRequired,
};

Review.defaultProps = {
user: 'Anonymous',
const mapStateToProps = (state, ownProps) => {
const review = state.reviews[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.

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

return {
user: state.users[review.userId].name || 'Anonymous',
text: review.text,
rating: review.rating,
};
};

export default Review;
export default connect(mapStateToProps)(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, restaurantId }) => {
return (
<div className={styles.reviews}>
{reviews.map((review) => (
<Review key={review.id} {...review} />
{reviews.map((id) => (
<Review key={id} id={id} />
))}
<ReviewForm />
<ReviewForm restaurantId={restaurantId} />
</div>
);
};

Reviews.propTypes = {
reviews: PropTypes.arrayOf(
PropTypes.shape({
id: PropTypes.string.isRequired,
}).isRequired
).isRequired,
reviews: PropTypes.array.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 = (review) => ({
type: ADD_REVIEW,
payload: { review },
});
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';
22 changes: 22 additions & 0 deletions src/redux/middleware/addReview.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import { v4 as uuidv4 } from 'uuid';
import { ADD_REVIEW } from '../constants';

export default (store) => (next) => (action) => {
if (action.type === ADD_REVIEW) {
const userId = uuidv4();
const reviewId = uuidv4();

action.payload = {
Copy link
Owner

Choose a reason for hiding this comment

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

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

review: {
userId: userId,
reviewId: reviewId,
name: action.payload.review.name,
text: action.payload.review.text,
rating: action.payload.review.rating,
restaurantId: action.payload.review.restaurantId,
},
};
}

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,
});
21 changes: 19 additions & 2 deletions src/redux/reducer/restaurants.js
Original file line number Diff line number Diff line change
@@ -1,9 +1,26 @@
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:
return {
...restaurants,
[payload.review.restaurantId]: {
...restaurants[payload.review.restaurantId],
reviews: [
...restaurants[payload.review.restaurantId].reviews,
payload.review.reviewId,
],
},
};
default:
return restaurants;
}
Expand Down
20 changes: 18 additions & 2 deletions src/redux/reducer/reviews.js
Original file line number Diff line number Diff line change
@@ -1,9 +1,25 @@
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:
return {
...reviews,
[payload.review.reviewId]: {
id: payload.review.reviewId,
userId: payload.review.userId,
text: payload.review.text,
rating: payload.review.rating,
},
};
default:
return reviews;
}
Expand Down
24 changes: 24 additions & 0 deletions src/redux/reducer/users.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
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:
return {
...users,
[payload.review.userId]: {
id: payload.review.userId,
name: payload.review.name,
},
};
default:
return users;
}
};
12 changes: 12 additions & 0 deletions src/redux/selectors.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { createSelector } from 'reselect';
// const restaurantsSelector = (state) => state.restaurants;
const orderSelector = (state) => state.order;
const productsSelector = (state) => state.products;
const reviewSelector = (state) => state.reviews;

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

export const averageRatingSelector = (state, props) =>
createSelector(reviewSelector, (reviews) => {
const restaurantReviews = state.restaurants[props.id].reviews;
Copy link
Owner

Choose a reason for hiding this comment

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

лучше не делать одновременно и обычный селектор и createSelector

return Math.round(
restaurantReviews.reduce(
(acc, review) => reviews[review].rating + acc,
0
) / restaurantReviews.length
);
})(state);
3 changes: 2 additions & 1 deletion src/redux/store.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,11 @@ import { applyMiddleware, createStore } from 'redux';
import { composeWithDevTools } from 'redux-devtools-extension';
import reducer from './reducer';
import logger from './middleware/logger';
import addReview from './middleware/addReview';

const store = createStore(
reducer,
composeWithDevTools(applyMiddleware(logger))
composeWithDevTools(applyMiddleware(addReview, logger))
);

export default store;