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

hw4: add redusers, selectors, new review adding from form #65

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
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
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 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
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 Button from '../button';
import { decrement, increment } from '../../redux/actions';
import { orderSelectorById, productSelectorById } from '../../redux/selectors';

function Product({ product, amount, decrement, increment, fetchData }) {
useEffect(() => {
Expand Down Expand Up @@ -56,8 +57,8 @@ Product.propTypes = {
};

const mapStateToProps = (state, props) => ({
amount: state.order[props.id] || 0,
product: state.products[props.id],
amount: orderSelectorById(state, props),
product: productSelectorById(state, props),
});

// const mapDispatchToProps = {
Expand Down
35 changes: 20 additions & 15 deletions src/components/restaurant/restaurant.js
Original file line number Diff line number Diff line change
@@ -1,21 +1,21 @@
import { useMemo, useState } from 'react';
import { useState } 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 {
restaurantSelectorById,
averageRatingSelector,
} from '../../redux/selectors';

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

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

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

const tabs = [
{ id: 'menu', label: 'Menu' },
{ id: 'reviews', label: 'Reviews' },
Expand All @@ -28,22 +28,27 @@ 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 reviews={reviews} key={id} restaurantId={restaurantId} />
)}
</div>
);
};

Restaurant.propTypes = {
restaurantId: PropTypes.string.isRequired,
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),
reviews: PropTypes.arrayOf(PropTypes.string),
}).isRequired,
averageRating: PropTypes.number,
};

export default Restaurant;
const mapStateToProps = (state, props) => ({
restaurant: restaurantSelectorById(state, props),
averageRating: averageRatingSelector(state, props),
});

export default connect(mapStateToProps)(Restaurant);
34 changes: 13 additions & 21 deletions src/components/restaurants/restaurants.js
Original file line number Diff line number Diff line change
@@ -1,41 +1,33 @@
import { useMemo, useState } from 'react';
import { useState } from 'react';
import { connect } from 'react-redux';
import PropTypes from 'prop-types';
import Restaurant from '../restaurant';
import Tabs from '../tabs';
import { tabsSelector } from '../../redux/selectors';

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

const tabs = useMemo(
() => restaurants.map(({ id, name }) => ({ id, label: name })),
[restaurants]
);

const activeRestaurant = useMemo(
() => restaurants.find((restaurant) => restaurant.id === activeId),
[activeId, restaurants]
);
function Restaurants({ tabs }) {
const [activeId, setActiveId] = useState(tabs[0].id);

return (
<div>
<Tabs tabs={tabs} onChange={setActiveId} activeId={activeId} />
<Restaurant restaurant={activeRestaurant} />
<Restaurant restaurantId={activeId} />
</div>
);
}

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

const mapStateToProps = (state) => ({
restaurants: state.restaurants,
tabs: tabsSelector(state),
});

export default connect(mapStateToProps)(Restaurants);
20 changes: 14 additions & 6 deletions src/components/reviews/review-form/review-form.js
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
import { connect } from 'react-redux';

import PropTypes from 'prop-types';
import useForm from '../../../hooks/use-form';
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 };

const ReviewForm = ({ onSubmit }) => {
const ReviewForm = ({ restaurantId, onSubmit }) => {
const INITIAL_VALUES = { name: '', text: '', rating: 3, restaurantId };
Copy link
Owner

Choose a reason for hiding this comment

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

в этом случае у нас будет очищаться форма при переходе на другой ресторан, раньше этого не было

const { values, handlers, reset } = useForm(INITIAL_VALUES);

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

export default connect(null, () => ({
onSubmit: (values) => console.log(values), // TODO
ReviewForm.propTypes = {
restaurantId: PropTypes.string.isRequired,
onSubmit: PropTypes.func,
};

export default connect(null, (dispatch) => ({
onSubmit: (values) => {
console.log(values); // TODO
dispatch(addreview(values));
},
}))(ReviewForm);
10 changes: 8 additions & 2 deletions src/components/reviews/review/review.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import PropTypes from 'prop-types';

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

const Review = ({ user, text, rating }) => (
<div className={styles.review} data-id="review">
Expand Down Expand Up @@ -31,4 +32,9 @@ Review.defaultProps = {
user: 'Anonymous',
};

export default Review;
const mapStateToProps = (state, props) => {
const { user, text, rating } = reviewSelectorById(state, props);
return { user, text, rating };
};

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 @@ -3,23 +3,19 @@ import Review from './review';
import ReviewForm from './review-form';
import styles from './reviews.module.css';

const Reviews = ({ reviews }) => {
const Reviews = ({ restaurantId, reviews }) => {
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,
};

export default 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, ADDREVIEW } 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 = (review) => ({ type: ADDREVIEW, 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 ADDREVIEW = 'ADDREVIEW';
7 changes: 7 additions & 0 deletions src/redux/middleware/uuidGenerator.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import { v4 as uuidv4 } from 'uuid';

export default (store) => (next) => (action) => {
action.review.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.review.userId = 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,
});
20 changes: 18 additions & 2 deletions src/redux/reducer/restaurants.js
Original file line number Diff line number Diff line change
@@ -1,9 +1,25 @@
import { normalizedRestaurants as defaultRestaurants } from '../../fixtures';
import { normalizedRestaurants } from '../../fixtures';
import { ADDREVIEW } from '../constants';

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

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

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

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

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

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

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

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

switch (type) {
case ADDREVIEW:
const { userId, name } = review;
return { ...users, [userId]: { userId, name } };

default:
return users;
}
};
Loading