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 hometask 5 #72

Open
wants to merge 3 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
77 changes: 41 additions & 36 deletions src/components/menu/menu.js
Original file line number Diff line number Diff line change
@@ -1,41 +1,46 @@
import React from 'react';
import PropTypes from 'prop-types';
import React, { useEffect } from 'react';
import { connect } from 'react-redux';
import Product from '../product';
import Basket from '../basket';

import styles from './menu.module.css';

class Menu extends React.Component {
static propTypes = {
menu: PropTypes.arrayOf(PropTypes.string.isRequired).isRequired,
};

state = { error: null };

componentDidCatch(error) {
this.setState({ error });
}

render() {
const { menu } = this.props;

if (this.state.error) {
return <p>В этом ресторане меню не доступно</p>;
import Loader from '../loader';

import {
productsSelector,
// productsListSelector,
productsLoadedSelector,
productsLoadingSelector,
} from '../../redux/selectors';
import { loadProducts } from '../../redux/actions';

const Menu = ({ products, restaurantId, loadProducts, loading, loaded }) => {
useEffect(() => {
if (!loading && !loaded) {
loadProducts(restaurantId);
}

return (
<div className={styles.menu}>
<div>
{menu.map((id) => (
<Product key={id} id={id} />
))}
</div>
<div>
<Basket />
</div>
}, [products, restaurantId, loading, loaded, loadProducts]);
Copy link
Owner

Choose a reason for hiding this comment

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

тут по хорошему лучше оставить только restaurantId, т.к. мы хотим начинать загрузку только при смене ресторана

if ((loading || !loaded) && !products) return <Loader />;
//
return (
<div className={styles.menu}>
<div>
{Object.values(products).map((product) => (
<Product key={product.id} product={product} />
))}
</div>
);
}
}

export default Menu;
<div>
<Basket />
</div>
</div>
);
};

export default connect(
(state, ownProps) => ({
products: productsSelector(state, ownProps.restaurantId),
loading: productsLoadingSelector(state, ownProps.restaurantId),
loaded: productsLoadedSelector(state, ownProps.restaurantId),
restaurantId: ownProps.restaurantId,
}),
{ loadProducts }
)(Menu);
3 changes: 1 addition & 2 deletions src/components/product/product.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import styles from './product.module.css';
import { decrement, increment } from '../../redux/actions';

import Button from '../button';
import { productAmountSelector, productSelector } from '../../redux/selectors';
import { productAmountSelector } from '../../redux/selectors';

const Product = ({ product, amount, increment, decrement, fetchData }) => {
useEffect(() => {
Expand Down Expand Up @@ -53,7 +53,6 @@ Product.propTypes = {

const mapStateToProps = createStructuredSelector({
amount: productAmountSelector,
product: productSelector,
});

const mapDispatchToProps = (dispatch, ownProps) => ({
Expand Down
10 changes: 5 additions & 5 deletions src/components/restaurant/restaurant.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,14 +6,14 @@ import Reviews from '../reviews';
import Banner from '../banner';
import Rate from '../rate';
import Tabs from '../tabs';
import { averageRatingSelector } from '../../redux/selectors';
// import { averageRatingSelector } from '../../redux/selectors';

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

Expand All @@ -36,5 +36,5 @@ Restaurant.propTypes = {
};

export default connect((state, props) => ({
averageRating: averageRatingSelector(state, props),
// averageRating: averageRatingSelector(state, props),
}))(Restaurant);
76 changes: 54 additions & 22 deletions src/components/reviews/review/review.js
Original file line number Diff line number Diff line change
@@ -1,28 +1,51 @@
import React from 'react';
import React, { useEffect } from 'react';
import PropTypes from 'prop-types';

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

const Review = ({ review: { user = 'Anonymous', 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} />

import {
usersSelector,
usersLoadedSelector,
usersLoadingSelector,
} from '../../../redux/selectors';

import { loadUsers } from '../../../redux/actions';

const Review = ({
review: { userId, text, rating },
users,
loading,
loaded,
loadUsers,
}) => {
useEffect(() => {
if (!loading && !loaded) {
loadUsers();
}
}, [users, loading, loaded, loadUsers]);

if ((loading || !loaded) && !users) return <Loader />;

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

Review.propTypes = {
review: PropTypes.shape({
Expand All @@ -32,6 +55,15 @@ Review.propTypes = {
}),
};

export default connect((state, props) => ({
review: reviewWitUserSelector(state, props),
}))(Review);
// export default connect((state, props) => ({
// review: reviewWitUserSelector(state, props),
// }))(Review);

export default connect(
(state, ownProps) => ({
users: usersSelector(state),
loading: usersLoadingSelector(state),
loaded: usersLoadedSelector(state),
}),
{ loadUsers }
)(Review);
31 changes: 24 additions & 7 deletions src/components/reviews/reviews.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,18 +4,27 @@ import Review from './review';
import ReviewForm from './review-form';
import styles from './reviews.module.css';
import { connect } from 'react-redux';

import Loader from '../loader';
import { loadReviews } from '../../redux/actions';

const Reviews = ({ reviews, restaurantId, loadReviews }) => {
import {
reviewsSelector,
reviewsLoadedSelector,
reviewsLoadingSelector,
} from '../../redux/selectors.js';

const Reviews = ({ reviews, restaurantId, loadReviews, loading, loaded }) => {
useEffect(() => {
loadReviews(restaurantId);
}, [loadReviews, restaurantId]);
if (!loading && !loaded) {
loadReviews(restaurantId);
}
}, [reviews, restaurantId, loading, loaded, loadReviews]);
if ((loading || !loaded) && !reviews) return <Loader />;

return (
<div className={styles.reviews}>
{reviews.map((id) => (
<Review key={id} id={id} />
{Object.values(reviews).map((review) => (
<Review key={review.id} review={review} />
))}
<ReviewForm restaurantId={restaurantId} />
</div>
Expand All @@ -27,4 +36,12 @@ Reviews.propTypes = {
reviews: PropTypes.arrayOf(PropTypes.string.isRequired).isRequired,
};

export default connect(null, { loadReviews })(Reviews);
export default connect(
(state, ownProps) => ({
reviews: reviewsSelector(state, ownProps.restaurantId),
loading: reviewsLoadingSelector(state, ownProps.restaurantId),
loaded: reviewsLoadedSelector(state, ownProps.restaurantId),
restaurantId: ownProps.restaurantId,
}),
{ loadReviews }
)(Reviews);
24 changes: 23 additions & 1 deletion src/redux/actions.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ import {
ADD_REVIEW,
LOAD_RESTAURANTS,
LOAD_REVIEWS,
LOAD_PRODUCTS,
LOAD_USERS,
REQUEST,
SUCCESS,
FAILURE,
Expand All @@ -25,13 +27,33 @@ export const loadRestaurants = () => ({
CallAPI: '/api/restaurants',
});

export const loadProducts = (restaurantId) => ({
type: LOAD_PRODUCTS,
payload: { restaurantId },
CallAPI: `/api/products?id=${restaurantId}`,
});

export const loadUsers = () => async (dispatch) => {
dispatch({ type: LOAD_USERS + REQUEST });
try {
const response = await fetch(`/api/users`).then((res) => res.json());
dispatch({ type: LOAD_USERS + SUCCESS, response });
} catch (error) {
dispatch({ type: LOAD_USERS + FAILURE, error });
}
};

export const loadReviews = (restaurantId) => async (dispatch) => {
dispatch({ type: LOAD_REVIEWS + REQUEST });
try {
const response = await fetch(
`/api/reviews?id=${restaurantId}`
).then((res) => res.json());
dispatch({ type: LOAD_REVIEWS + SUCCESS, response });
dispatch({
type: LOAD_REVIEWS + SUCCESS,
payload: { restaurantId },
response,
});
} catch (error) {
dispatch({ type: LOAD_REVIEWS + FAILURE, error });
}
Expand Down
2 changes: 2 additions & 0 deletions src/redux/constants.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ export const ADD_REVIEW = 'ADD_REVIEW';

export const LOAD_RESTAURANTS = 'LOAD_RESTAURANTS';
export const LOAD_REVIEWS = 'LOAD_REVIEWS';
export const LOAD_PRODUCTS = 'LOAD_PRODUCTS';
export const LOAD_USERS = 'LOAD_USERS';

export const REQUEST = '_REQUEST';
export const SUCCESS = '_SUCCESS';
Expand Down
42 changes: 39 additions & 3 deletions src/redux/reducer/products.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,47 @@
import { normalizedProducts } from '../../fixtures';
// import restaurant from '../../components/restaurant';
import { FAILURE, LOAD_PRODUCTS, REQUEST, SUCCESS } from '../constants';
import { arrToMap } from '../utils';

const initialState = {
initial: {
Copy link
Owner

Choose a reason for hiding this comment

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

зачем это состояние? я не нашел ни одного селектора, который это использует

entities: {},
loading: false,
loaded: false,
error: null,
},
};
// { [productId]: product }
const reducer = (state = arrToMap(normalizedProducts), action) => {
const { type } = action;
const reducer = (state = initialState, action) => {
const { type, payload, response, error } = action;

switch (type) {
case LOAD_PRODUCTS + REQUEST:
return {
...state,
initial: {
loading: true,
error: null,
},
};
case LOAD_PRODUCTS + SUCCESS:
const restaurantId = payload.restaurantId;
return {
...state,
[restaurantId]: {
entities: arrToMap(response),
loading: false,
loaded: true,
},
};
case LOAD_PRODUCTS + FAILURE:
return {
...state,
initial: {
loading: false,
loaded: false,
error,
},
};
default:
return state;
}
Expand Down
Loading