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

ДЗ4 #63

Open
wants to merge 1 commit 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 .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
.env.development.local
.env.test.local
.env.production.local
.idea

npm-debug.log*
yarn-debug.log*
Expand Down
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
6 changes: 1 addition & 5 deletions src/components/menu/menu.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,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,
};

state = { error: null };
Expand Down
8 changes: 6 additions & 2 deletions src/components/rate/rate.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,14 @@ import PropTypes from 'prop-types';

import Star from './star';

const Rate = ({ value, onChange }) => (
const Rate = ({ value, onChange, readOnly = false }) => (
<div>
{[...Array(5)].map((_, i) => (
<Star key={i} checked={i <= value - 1} onClick={() => onChange(i + 1)} />
<Star
key={i}
checked={i <= value - 1}
onClick={readOnly ? undefined : () => onChange(i + 1)}
/>
))}
</div>
);
Expand Down
21 changes: 12 additions & 9 deletions src/components/restaurant/restaurant.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import React, { useMemo } from 'react';
import { connect } from 'react-redux';
import PropTypes from 'prop-types';
import Menu from '../menu';
import Reviews from '../reviews';
Expand All @@ -7,7 +8,7 @@ import Rate from '../rate';
import Tabs from '../tabs';

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

const averageRating = useMemo(() => {
const total = reviews.reduce((acc, { rating }) => acc + rating, 0);
Expand All @@ -16,7 +17,10 @@ const Restaurant = ({ restaurant }) => {

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

return (
Expand All @@ -31,14 +35,13 @@ const Restaurant = ({ restaurant }) => {

Restaurant.propTypes = {
restaurant: PropTypes.shape({
id: PropTypes.string.isRequired,
name: PropTypes.string,
menu: PropTypes.array,
reviews: PropTypes.arrayOf(
PropTypes.shape({
rating: PropTypes.number.isRequired,
}).isRequired
).isRequired,
menu: PropTypes.arrayOf(PropTypes.string).isRequired,
reviews: PropTypes.arrayOf(PropTypes.string).isRequired,
}).isRequired,
};

export default Restaurant;
export default connect((state, { id }) => ({
restaurant: state.restaurants[id],
}))(Restaurant);
16 changes: 11 additions & 5 deletions src/components/restaurants/restaurants.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,16 +5,22 @@ import Restaurant from '../restaurant';
import Tabs from '../tabs';

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

const tabs = ids.map((id) => {
const restaurant = restaurants[id];

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

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

Restaurants.propTypes = {
restaurants: PropTypes.arrayOf(
restaurants: PropTypes.objectOf(
PropTypes.shape({
id: PropTypes.string.isRequired,
}).isRequired
Expand Down
9 changes: 4 additions & 5 deletions src/components/reviews/review-form/review-form.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,15 +5,16 @@ import Rate from '../../rate';
import styles from './review-form.module.css';
import { connect } from 'react-redux';
import Button from '../../button';
import { createReview } from '../../../redux/actions';

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

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

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

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

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

import { makeGetReview, makeGetReviewUser } from '../../../redux/selectors';
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} />
const Review = ({ review, user }) => {
const { text, rating } = review;
const userName = useMemo(() => user.name || 'Anonymous', [user]);

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

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

Review.defaultProps = {
user: 'Anonymous',
const makeMapStateToProps = (initialState, { id }) => {
const getReview = makeGetReview(id);
const getReviewUser = makeGetReviewUser(id);

return (state) => ({
review: getReview(state),
Copy link
Owner

Choose a reason for hiding this comment

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

тут лучше не делать каррирования, а сделать review: reviewSelecor(state, props) На занятии расскажу почему

user: getReviewUser(state),
});
};

export default Review;
export default connect(makeMapStateToProps)(Review);
15 changes: 6 additions & 9 deletions src/components/reviews/reviews.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,23 +4,20 @@ 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.arrayOf(PropTypes.string).isRequired,
restaurantId: PropTypes.string.isRequired,
};

export default Reviews;
7 changes: 6 additions & 1 deletion src/redux/actions.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,10 @@
import { INCREMENT, DECREMENT, REMOVE } from './constants';
import { INCREMENT, DECREMENT, REMOVE, CREATE_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 createReview = (values, meta) => ({
type: CREATE_REVIEW,
payload: { ...values },
meta,
Copy link
Owner

Choose a reason for hiding this comment

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

ну это не совсем meta, restaurantId скорее в payload должен идти

});
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 CREATE_REVIEW = 'CREATE_REVIEW';
18 changes: 18 additions & 0 deletions src/redux/middleware/generateId.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import { v4 as generate } from 'uuid';
import { CREATE_REVIEW } from '../constants';

const generateId = (store) => (next) => (action) => {
if (action.type === CREATE_REVIEW) {
next({
...action,
payload: {
...action.payload,
id: generate(),
},
});
} else {
next(action);
}
};

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

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

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

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

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

switch (type) {
case CREATE_REVIEW:
const { id } = payload;
const { restaurantId } = meta;
const restaurant = restaurants[restaurantId];
const { reviews } = restaurant;

return {
...restaurants,
[restaurantId]: {
...restaurant,
reviews: reviews ? reviews.concat(id) : [id],
},
};
default:
return restaurants;
}
Expand Down
17 changes: 15 additions & 2 deletions src/redux/reducer/reviews.js
Original file line number Diff line number Diff line change
@@ -1,9 +1,22 @@
import { normalizedReviews as defaultReviews } from '../../fixtures';
import { normalizedReviews } from '../../fixtures';
import { CREATE_REVIEW } 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 CREATE_REVIEW:
const { id, text, rate: rating, userId } = payload;

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

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

const reducer = (users = 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.

нету добавления пользователя по CREATE_REVIEW

Copy link
Author

Choose a reason for hiding this comment

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

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

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 users;
}
};

export default reducer;
Loading