-
Notifications
You must be signed in to change notification settings - Fork 20
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
HT-5: fetch data asynchronously #71
Open
vskosp
wants to merge
1
commit into
koretskiyav:master
Choose a base branch
from
vskosp:hw-5
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,14 +1,20 @@ | ||
import { normalizedProducts } from '../../fixtures'; | ||
import { arrToMap } from '../utils'; | ||
import { combineReducers } from 'redux'; | ||
import { arrToMap, listByIdReducer } from '../utils'; | ||
import { LOAD_PRODUCTS, SUCCESS } from '../constants' | ||
|
||
// { [productId]: product } | ||
const reducer = (state = arrToMap(normalizedProducts), action) => { | ||
const { type } = action; | ||
const entities = (state = {}, action) => { | ||
const { type, response } = action; | ||
|
||
switch (type) { | ||
case LOAD_PRODUCTS + SUCCESS: | ||
return { ...state, ...arrToMap(response) }; | ||
default: | ||
return state; | ||
} | ||
}; | ||
|
||
export default reducer; | ||
export default combineReducers({ | ||
entities, | ||
listByRestaurant: listByIdReducer(LOAD_PRODUCTS) | ||
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -3,7 +3,7 @@ import { getById } from './utils'; | |
|
||
const restaurantsSelector = (state) => state.restaurants.entities; | ||
const orderSelector = (state) => state.order; | ||
const productsSelector = (state) => state.products; | ||
const productsSelector = (state) => state.products.entities; | ||
|
||
export const restaurantsLoadingSelector = (state) => state.restaurants.loading; | ||
export const restaurantsLoadedSelector = (state) => state.restaurants.loaded; | ||
|
@@ -29,7 +29,7 @@ export const totalSelector = createSelector( | |
orderProducts.reduce((acc, { subtotal }) => acc + subtotal, 0) | ||
); | ||
|
||
const reviewsSelector = (state) => state.reviews; | ||
const reviewsSelector = (state) => state.reviews.entities; | ||
const usersSelector = (state) => state.users; | ||
|
||
export const restaurantsListSelector = createSelector( | ||
|
@@ -53,9 +53,32 @@ export const averageRatingSelector = createSelector( | |
reviewsSelector, | ||
(_, { reviews }) => reviews, | ||
(reviews, ids) => { | ||
const ratings = ids.map((id) => reviews[id].rating); | ||
const ratings = ids.map((id) => reviews[id]?.rating); | ||
return Math.round( | ||
ratings.reduce((acc, rating) => acc + rating) / ratings.length | ||
); | ||
} | ||
); | ||
|
||
const restaurantProductsSelector = (state, props) => state.products.listByRestaurant[props.restaurantId]; | ||
const restaurantReviewsSelector = (state, props) => state.reviews.listByRestaurant[props.restaurantId || props.id]; | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. лучше пропу переименовать, чтобы везде было, к примеру, props.restaurantId |
||
|
||
export const isRestaurantProductsLoading = createSelector( | ||
restaurantProductsSelector, | ||
(restaurantProducts) => restaurantProducts && restaurantProducts.isLoading | ||
); | ||
|
||
export const isRestaurantProductsLoaded = createSelector( | ||
restaurantProductsSelector, | ||
(restaurantProducts) => restaurantProducts && restaurantProducts.isLoaded | ||
); | ||
|
||
export const isRestaurantReviewsLoading = createSelector( | ||
restaurantReviewsSelector, | ||
(restaurantReviews) => restaurantReviews && restaurantReviews.isLoading | ||
); | ||
|
||
export const isRestaurantReviewsLoaded = createSelector( | ||
restaurantReviewsSelector, | ||
(restaurantReviews) => restaurantReviews && restaurantReviews.isLoaded | ||
); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,4 +1,5 @@ | ||
import { createSelector } from 'reselect'; | ||
import {FAILURE, REQUEST, SUCCESS} from './constants'; | ||
|
||
export const arrToMap = (arr) => | ||
arr.reduce((acc, item) => ({ ...acc, [item.id]: item }), {}); | ||
|
@@ -9,3 +10,36 @@ export const getById = (selector, defaultValue) => | |
(_, props) => props.id, | ||
(entity, id) => entity[id] || defaultValue | ||
); | ||
|
||
export const listByIdReducer = (actionType) => (state = {}, action) => { | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. прикольное решение |
||
const { type, params } = action; | ||
|
||
switch (type) { | ||
case actionType + REQUEST: | ||
return { | ||
...state, | ||
[params.id]: { | ||
isLoading: true, | ||
isLoaded: false | ||
} | ||
}; | ||
case actionType + SUCCESS: | ||
return { | ||
...state, | ||
[params.id]: { | ||
isLoading: false, | ||
isLoaded: true | ||
} | ||
}; | ||
case actionType + FAILURE: | ||
return { | ||
...state, | ||
[params.id]: { | ||
isLoading: false, | ||
isLoaded: false | ||
} | ||
}; | ||
default: | ||
return state; | ||
} | ||
}; |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
тут еще нужно проверить поменялся ли restaurantId, чтобы логика из loadProducts вызывалась только при смене ресторана
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
она не будет вызываться для уже загруженных ресторанов из-за этой проверки (isLoading и isLoaded будут передаваться для текущего ресторана) https://github.com/koretskiyav/react-2020-11-13/pull/71/files#diff-4d8fc5329143e8a6d6c5486e865a6ac6ad20a19f415fbf280fab745160f398aeR62
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
сейчас да, но код часто меняется и это менее очевидно, чем вызывать это только при смене ресторана. То есть если я зайду в этот код, через 3 месяца, я хочу понять что тут происходит и какая логика заложена. Я хочу в коде видеть, буквально "если у нас поменялся ресторан идем грузить продукты".
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
явное всегда лучше неявного
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
согласен