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

Ershovro/homework 5 #73

Open
wants to merge 4 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: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -21,3 +21,6 @@ node_modules
npm-debug.log*
yarn-debug.log*
yarn-error.log*

package-lock.json
.idea
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@
"web-vitals": "^0.2.4"
},
"scripts": {
"start": "concurrently \"react-scripts start\" \"yarn api\"",
"start": "concurrently \"react-scripts start\" \"npm run api\"",
"api": "node simple_api/server.js",
"build": "react-scripts build",
"test": "react-scripts test",
Expand Down
33 changes: 31 additions & 2 deletions src/components/menu/menu.js
Original file line number Diff line number Diff line change
@@ -1,13 +1,19 @@
import React from 'react';
import { connect } from 'react-redux';
import PropTypes from 'prop-types';
import Product from '../product';
import Basket from '../basket';
import { loadProducts } from '../../redux/actions';
import { menuLoadedSelector, menuLoadingSelector } from '../../redux/selectors';
import { createStructuredSelector } from 'reselect';

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

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

state = { error: null };
Expand All @@ -16,13 +22,31 @@ class Menu extends React.Component {
this.setState({ error });
}

componentDidMount() {
if (!this.props.loading && !this.props.loaded) {
this.props.loadProducts(this.props.restaurantId);
}
}

componentDidUpdate(prevProps, prevState, snapshot) {
if (
this.props.restaurantId !== prevProps.restaurantId &&
!this.props.loading &&
!this.props.loaded
) {
this.props.loadProducts(this.props.restaurantId);
}
}

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

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

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

return (
<div className={styles.menu}>
<div>
Expand All @@ -38,4 +62,9 @@ class Menu extends React.Component {
}
}

export default Menu;
const mapStateToProps = createStructuredSelector({
loading: menuLoadingSelector,
loaded: menuLoadedSelector,
});

export default connect(mapStateToProps, { loadProducts })(Menu);
10 changes: 3 additions & 7 deletions src/components/restaurant/restaurant.js
Original file line number Diff line number Diff line change
@@ -1,16 +1,14 @@
import React 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';
import { averageRatingSelector } from '../../redux/selectors';

const Restaurant = ({ id, name, menu, reviews, averageRating }) => {
const Restaurant = ({ id, name, menu, reviews, averageRating = 0 }) => {
const tabs = [
{ title: 'Menu', content: <Menu menu={menu} /> },
{ title: 'Menu', content: <Menu menu={menu} restaurantId={id} /> },
{
title: 'Reviews',
content: <Reviews reviews={reviews} restaurantId={id} />,
Expand All @@ -35,6 +33,4 @@ Restaurant.propTypes = {
averageRating: PropTypes.number,
};

export default connect((state, props) => ({
averageRating: averageRatingSelector(state, props),
}))(Restaurant);
export default Restaurant;
16 changes: 8 additions & 8 deletions src/components/restaurants/restaurants.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import {
restaurantsLoadingSelector,
} from '../../redux/selectors';
import { loadRestaurants } from '../../redux/actions';
import { createStructuredSelector } from 'reselect';

const Restaurants = ({ restaurants, loadRestaurants, loading, loaded }) => {
useEffect(() => {
Expand All @@ -34,11 +35,10 @@ Restaurants.propTypes = {
).isRequired,
};

export default connect(
(state) => ({
restaurants: restaurantsListSelector(state),
loading: restaurantsLoadingSelector(state),
loaded: restaurantsLoadedSelector(state),
}),
{ loadRestaurants }
)(Restaurants);
const mapStateToProps = createStructuredSelector({
restaurants: restaurantsListSelector,
loading: restaurantsLoadingSelector,
loaded: restaurantsLoadedSelector,
});

export default connect(mapStateToProps, { loadRestaurants })(Restaurants);
19 changes: 16 additions & 3 deletions src/components/reviews/reviews.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,22 @@ import Review from './review';
import ReviewForm from './review-form';
import styles from './reviews.module.css';
import { connect } from 'react-redux';
import { createStructuredSelector } from 'reselect';

import {
reviewsOfRestaurantsLoadingSelector,
reviewsOfRestaurantsLoadedSelector,
} from '../../redux/selectors';
import { loadReviews } from '../../redux/actions';
import Loader from '../loader';

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

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

return (
<div className={styles.reviews}>
{reviews.map((id) => (
Expand All @@ -27,4 +35,9 @@ Reviews.propTypes = {
reviews: PropTypes.arrayOf(PropTypes.string.isRequired).isRequired,
};

export default connect(null, { loadReviews })(Reviews);
const mapStateToProps = createStructuredSelector({
loading: reviewsOfRestaurantsLoadingSelector,
loaded: reviewsOfRestaurantsLoadedSelector,
});

export default connect(mapStateToProps, { loadReviews })(Reviews);
49 changes: 42 additions & 7 deletions 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,14 +27,47 @@ export const loadRestaurants = () => ({
CallAPI: '/api/restaurants',
});

export const loadReviews = (restaurantId) => async (dispatch) => {
dispatch({ type: LOAD_REVIEWS + REQUEST });
export const loadReviews = (restaurantId) => async (dispatch, getState) => {
dispatch({ type: LOAD_REVIEWS + REQUEST, payload: { restaurantId } });
try {
const response = await fetch(
`/api/reviews?id=${restaurantId}`
).then((res) => res.json());
dispatch({ type: LOAD_REVIEWS + SUCCESS, response });
const [response] = await Promise.all([
fetch(`/api/reviews?id=${restaurantId}`).then((res) => res.json()),
getState().users.loaded ? Promise.resolve() : loadUsers(dispatch),
Copy link
Owner

Choose a reason for hiding this comment

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

тут нужно использовать usersLoadedSelector, так же сделать проверку что они сейчас не грузятся

]);

dispatch({
type: LOAD_REVIEWS + SUCCESS,
response,
payload: { restaurantId },
});
} catch (error) {
dispatch({ type: LOAD_REVIEWS + FAILURE, error });
dispatch({
type: LOAD_REVIEWS + FAILURE,
error,
payload: { 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 loadProducts = (restaurantId) => ({
type: LOAD_PRODUCTS,
CallAPI: `/api/products?id=${restaurantId}`,
restaurantId,
});
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
32 changes: 28 additions & 4 deletions src/redux/reducer/products.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,35 @@
import { normalizedProducts } from '../../fixtures';
import produce from 'immer';
import { arrToMap } from '../utils';
import { LOAD_PRODUCTS, REQUEST, SUCCESS, FAILURE } from '../constants';

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

const reducer = (state = initialState, action) => {
const { type, restaurantId, response, error } = action;

switch (type) {
case LOAD_PRODUCTS + REQUEST:
return produce(state, (draft) => {
draft.loading[restaurantId] = true;
draft.error[restaurantId] = null;
});
case LOAD_PRODUCTS + SUCCESS:
return produce(state, (draft) => {
Object.assign(draft.entities, arrToMap(response));
draft.loading[restaurantId] = false;
draft.loaded[restaurantId] = true;
});
case LOAD_PRODUCTS + FAILURE:
return produce(state, (draft) => {
draft.loading[restaurantId] = false;
draft.loaded[restaurantId] = false;
draft.error[restaurantId] = error;
});
default:
return state;
}
Expand Down
47 changes: 39 additions & 8 deletions src/redux/reducer/reviews.js
Original file line number Diff line number Diff line change
@@ -1,17 +1,48 @@
import { ADD_REVIEW } from '../constants';
import { normalizedReviews } from '../../fixtures';
import {
ADD_REVIEW,
LOAD_REVIEWS,
REQUEST,
SUCCESS,
FAILURE,
} from '../constants';
import produce from 'immer';
import { arrToMap } from '../utils';

const reducer = (state = arrToMap(normalizedReviews), action) => {
const { type, payload, reviewId, userId } = action;
const initialState = {
entities: {},
loading: {},
loaded: {},
error: {},
};

const reducer = (state = initialState, action) => {
const { type, payload, reviewId, userId, response, error } = action;

switch (type) {
case LOAD_REVIEWS + REQUEST:
return produce(state, (draft) => {
draft.loading[payload.restaurantId] = true;
draft.error[payload.restaurantId] = null;
});

case LOAD_REVIEWS + SUCCESS:
return produce(state, (draft) => {
Object.assign(draft.entities, arrToMap(response));
draft.loading[payload.restaurantId] = false;
draft.loaded[payload.restaurantId] = true;
});
case LOAD_REVIEWS + FAILURE:
return produce(state, (draft) => {
draft.loading[payload.restaurantId] = false;
draft.loaded[payload.restaurantId] = false;
draft.error[payload.restaurantId] = error;
});
case ADD_REVIEW:
const { text, rating } = payload.review;
return {
...state,
[reviewId]: { id: reviewId, userId, text, rating },
};

return produce(state, (draft) => {
draft.entities[reviewId] = { id: reviewId, userId, text, rating };
});
default:
return state;
}
Expand Down
34 changes: 30 additions & 4 deletions src/redux/reducer/users.js
Original file line number Diff line number Diff line change
@@ -1,12 +1,38 @@
import produce from 'immer';
import { ADD_REVIEW } from '../constants';
import { normalizedUsers } from '../../fixtures';
import {
ADD_REVIEW,
LOAD_USERS,
REQUEST,
SUCCESS,
FAILURE,
} from '../constants';
import { arrToMap } from '../utils';

const reducer = produce((draft = arrToMap(normalizedUsers), action) => {
const { type, payload, userId } = action;
const initialState = {
entities: {},
loading: false,
loaded: false,
error: null,
};

const reducer = produce((draft = initialState, action) => {
const { type, payload, userId, response, error } = action;

switch (type) {
case LOAD_USERS + REQUEST:
draft.loading = true;
draft.error = null;
break;
case LOAD_USERS + SUCCESS:
draft.entities = arrToMap(response);
draft.loading = false;
draft.loaded = true;
break;
case LOAD_USERS + FAILURE:
draft.loading = false;
draft.loaded = false;
draft.error = error;
break;
case ADD_REVIEW:
const { name } = payload.review;
draft[userId] = { id: userId, name };
Expand Down
Loading