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

Feature/home task 4 #67

Open
wants to merge 6 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
3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,8 @@
"react-scripts": "4.0.3",
"redux": "^4.1.1",
"redux-devtools-extension": "^2.13.9",
"reselect": "^4.0.0"
"reselect": "^4.0.0",
"uuid": "^8.3.2"
},
"scripts": {
"start": "react-scripts start",
Expand Down
15 changes: 10 additions & 5 deletions src/components/restaurant/restaurant.js
Original file line number Diff line number Diff line change
@@ -1,20 +1,21 @@
import { useMemo, useState } 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';

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

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

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

const tabs = [
{ id: 'menu', label: 'Menu' },
Expand All @@ -28,7 +29,7 @@ const Restaurant = ({ restaurant }) => {
</Banner>
<Tabs tabs={tabs} activeId={activeTab} onChange={setActiveTab} />
{activeTab === 'menu' && <Menu menu={menu} key={id} />}
{activeTab === 'reviews' && <Reviews reviews={reviews} />}
{activeTab === 'reviews' && <Reviews currentRestaurant={restaurant.id}/>}
</div>
);
};
Expand All @@ -46,4 +47,8 @@ Restaurant.propTypes = {
}).isRequired,
};

export default Restaurant;
const mapStateToProps = (state) => ({
allReviews: state.reviews,
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 connect(mapStateToProps)(Restaurant);
12 changes: 6 additions & 6 deletions src/components/restaurants/restaurants.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,17 +5,17 @@ import Restaurant from '../restaurant';
import Tabs from '../tabs';

function Restaurants({ restaurants }) {
const [activeId, setActiveId] = useState(restaurants[0].id);
const [firstKey] = Object.keys(restaurants);
const [activeId, setActiveId] = useState(restaurants[firstKey].id);

const tabs = useMemo(
() => restaurants.map(({ id, name }) => ({ id, label: name })),
() => Object.keys(restaurants).map((key) => {
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: restaurants[key].id, label: restaurants[key].name};
}),
[restaurants]
);

const activeRestaurant = useMemo(
() => restaurants.find((restaurant) => restaurant.id === activeId),
[activeId, restaurants]
);
const activeRestaurant = restaurants[activeId]

return (
<div>
Expand Down
5 changes: 3 additions & 2 deletions src/components/reviews/review-form/review-form.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import Rate from '../../rate';
import Button from '../../button';

import styles from './review-form.module.css';
import {addReview} from "../../../redux/actions";

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

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) => ({
onSubmit: (values) => {dispatch(addReview(values))}, // TODO
}))(ReviewForm);
56 changes: 34 additions & 22 deletions src/components/reviews/review/review.js
Original file line number Diff line number Diff line change
@@ -1,34 +1,46 @@
import PropTypes from 'prop-types';

import { connect } from 'react-redux';
import Rate from '../../rate';
import styles from './review.module.css';

const Review = ({ user, text, rating }) => (
<div className={styles.review} data-id="review">
<div className={styles.content}>
<div>
<h4 className={styles.name} data-id="review-user">
{user}
</h4>
<p className={styles.comment} data-id="review-text">
{text}
</p>
</div>
<div className={styles.rate}>
<Rate value={rating} />
function Review({review, users}) {
const user = users[review?.userId] ? users[review?.userId] : null;
Copy link
Owner

Choose a reason for hiding this comment

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

это все необходимо вынести в селекторы

return (
<div className={styles.review} data-id="review">
<div className={styles.content}>
<div>
<h4 className={styles.name} data-id="review-user">
{ user && user.name ? user.name : "Anonymous"}
</h4>
<p className={styles.comment} data-id="review-text">
{review && (review.text)}
</p>
</div>
<div className={styles.rate}>
{review && review.rating && (<Rate value={review.rating}/>)}
</div>
</div>
</div>
</div>
);
);
};

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

Review.defaultProps = {
user: 'Anonymous',
const mapStateToProps = (state, props) => {
return {
review: state.reviews[props.reviewId],
users: state.users
}
};

export default Review;
export default connect(mapStateToProps)(Review);
17 changes: 12 additions & 5 deletions src/components/reviews/reviews.js
Original file line number Diff line number Diff line change
@@ -1,15 +1,18 @@
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import Review from './review';
import ReviewForm from './review-form';
import styles from './reviews.module.css';
import {restaurantsSelector} from "../../redux/selectors";

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

{restaurants[currentRestaurant].reviews.map((id) => (
<Review key={id} reviewId={id} />
))}
<ReviewForm />
<ReviewForm id={currentRestaurant}/>
</div>
);
};
Expand All @@ -22,4 +25,8 @@ Reviews.propTypes = {
).isRequired,
};

export default Reviews;
const mapStateToProps = (state, props) => ({
restaurants: restaurantsSelector(state)
});

export default connect(mapStateToProps)(Reviews);
3 changes: 2 additions & 1 deletion src/redux/actions.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { DECREMENT, INCREMENT, REMOVE } from './constants';
import { DECREMENT, INCREMENT, REMOVE, ADD_REVIEW } from './constants';

export const increment = (id) => ({ type: INCREMENT, id });
export const decrement = (id) => ({ type: DECREMENT, id });
export const remove = (id) => ({ type: REMOVE, id });
export const addReview = (params) => ({ type: ADD_REVIEW, payload: params});
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';
10 changes: 10 additions & 0 deletions src/redux/middleware/uuidGenerator.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import { v4 as uuidv4 } from 'uuid';
import { ADD_REVIEW } from "../constants";

export default (store) => (next) => (action) => {
if (action.type === ADD_REVIEW) {
action.payload.id = uuidv4();
Copy link
Owner

Choose a reason for hiding this comment

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

не стоит мутировать action, расскажу при разборе домашки почему

action.payload.uuid = uuidv4();
}
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
});
7 changes: 6 additions & 1 deletion src/redux/reducer/restaurants.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,9 @@
import { normalizedRestaurants as defaultRestaurants } from '../../fixtures';
import {normalizedRestaurants} from '../../fixtures';

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

export default (restaurants = defaultRestaurants, action) => {
const { type } = action;
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:
return { ...reviews, [payload.id]: {
name: payload.name,
rating: payload.rating,
text: payload.text,
userId: payload.uuid
}
};
default:
return reviews;
}
Expand Down
15 changes: 15 additions & 0 deletions src/redux/reducer/users.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import { normalizedUsers } from '../../fixtures';

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

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

switch (type) {
Copy link
Owner

Choose a reason for hiding this comment

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

пропущено добавление нового юзера из ревью

default:
return products;
}
};
16 changes: 16 additions & 0 deletions src/redux/selectors.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,9 @@ import { createSelector } from 'reselect';
// const restaurantsSelector = (state) => state.restaurants;
const productsSelector = (state) => state.products;
const orderSelector = (state) => state.order;
const reviewsSelector = (state) => state.reviews;
export const usersSelector = (state) => state.users;
export const restaurantsSelector = (state) => state.restaurants;

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

export const getReviewsSelector = createSelector(
[reviewsSelector],
(reviewsSelector) =>
Object.keys(reviewsSelector).map((reviewId) => reviewsSelector[reviewId])

);

export const getUsersSelector = createSelector(
[usersSelector],
(usersSelector) =>
Object.keys(usersSelector).map((userId) => usersSelector[userId])
);
5 changes: 4 additions & 1 deletion src/redux/store.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,13 @@ import { applyMiddleware, createStore } from 'redux';
import { composeWithDevTools } from 'redux-devtools-extension';

import logger from './middleware/logger';
import uuidGenerator from './middleware/uuidGenerator';

import reducer from './reducer';

const middlewares = [logger, uuidGenerator];

export default createStore(
reducer,
composeWithDevTools(applyMiddleware(logger))
applyMiddleware(...middlewares),
);