Skip to content

HT6 #38

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

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open

HT6 #38

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
9 changes: 8 additions & 1 deletion src/App.js
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
import React, { Component } from 'react'
import { Route, NavLink, Switch } from 'react-router-dom'
import { NavLink, Route, Switch } from 'react-router-dom'
import ArticlesRoute from './components/routes/articles'
import Filters from './components/filters'
import UserForm from './components/user-form'
import Counter from './components/counter'
import CommentsPage from './components/routes/comments-page'

class App extends Component {
render() {
Expand All @@ -27,6 +28,11 @@ class App extends Component {
Counter
</NavLink>
</div>
<div>
<NavLink to="/comments" activeStyle={{ color: 'red' }}>
Comments
</NavLink>
</div>
</div>
</div>
<UserForm />
Expand All @@ -35,6 +41,7 @@ class App extends Component {
<Route path="/filters" component={Filters} />
<Route path="/articles/new" render={() => <h1>New article form</h1>} />
<Route path="/articles" component={ArticlesRoute} />
<Route path="/comments/:page?" component={CommentsPage} />
<Route path="/" render={() => <h1>Not Found Page</h1>} />
</Switch>
</div>
Expand Down
30 changes: 25 additions & 5 deletions src/ac/index.js
Original file line number Diff line number Diff line change
@@ -1,15 +1,16 @@
import {
INCREMENT,
DELETE_ARTICLE,
ADD_COMMENT,
CHANGE_DATE_RANGE,
CHANGE_SELECTION,
ADD_COMMENT,
DELETE_ARTICLE,
INCREMENT,
LOAD_ALL_ARTICLES,
LOAD_ARTICLE,
LOAD_ARTICLE_COMMENTS,
START,
SUCCESS,
LOAD_ARTICLE_COMMENTS
SUCCESS
} from '../constants'
import { LOAD_COMMENTS } from '../constants/index'

export function increment() {
return {
Expand Down Expand Up @@ -88,3 +89,22 @@ export function loadArticleComments(articleId) {
callAPI: `/api/comment?article=${articleId}`
}
}

export function loadComments(page) {
page = +page
return async (dispatch) => {
dispatch({
Copy link
Owner

Choose a reason for hiding this comment

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

каждую страницу надо было загружать только один раз, не вижу кеширования

Copy link
Author

Choose a reason for hiding this comment

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

https://github.com/romabelka/basic-react-1102/blob/master/src/ac/index.js#L66

Здесь тоже нет кеширования.

Кеширование у нас ведь делается на уровне connect()

https://github.com/Ozerich/basic-react-1102/blob/a6e65d2148d7aba2ddbe095f6256e4597810575e/src/components/comments-page-list.js#L26

type: LOAD_COMMENTS + START,
payload: { page }
})

const rawRes = await fetch(`/api/comment/?limit=5&offset=${(page - 1) * 5}`)
const response = await rawRes.json()

dispatch({
type: LOAD_COMMENTS + SUCCESS,
payload: { page },
response
})
}
}
33 changes: 33 additions & 0 deletions src/components/comments-navigation.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import React, { Component } from 'react'
import { Link } from 'react-router-dom'
import PropTypes from 'prop-types'

class CommentsNavigation extends Component {
static propTypes = {
activePage: PropTypes.number,
hasNext: PropTypes.bool
}

static defaultProps = {
activePage: 1,
hasNext: false
}

render() {
const { activePage, hasNext } = this.props

return (
<div>
{activePage > 1 ? this.renderPageLink('Prev', activePage - 1) : null}
<strong style={{ margin: '0 20px', display: 'inline-block' }}>Page: {activePage}</strong>
{hasNext ? this.renderPageLink('Next', activePage + 1) : null}
</div>
)
}

renderPageLink(label, page) {
return <Link to={`/comments/${page}`}>{label}</Link>
}
}

export default CommentsNavigation
44 changes: 44 additions & 0 deletions src/components/comments-page-list.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
import React, { useEffect } from 'react'
import { connect } from 'react-redux'
import { loadComments } from '../ac/index'

import { commentsByPageSelector } from '../selectors/comments'

function CommentsPageList(props) {
useCheckAndFetch(props)

const { items } = props

if (!items) {
return null
}

return items.map((model) => {
return (
<p>
Copy link
Owner

Choose a reason for hiding this comment

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

key не забывай

{model.text} <br />
<b>by {model.user}</b>
</p>
)
})
}

function useCheckAndFetch(props) {
useEffect(() => {
const { items, page, loadComments } = props
if (!items) {
loadComments(page)
}
}, [props.page])
}

function mapStateToProps(state, ownProps) {
return {
items: commentsByPageSelector(state, ownProps)
}
}

export default connect(
mapStateToProps,
{ loadComments }
)(CommentsPageList)
26 changes: 26 additions & 0 deletions src/components/routes/comments-page.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import React from 'react'
import { connect } from 'react-redux'
import CommentsNavigation from '../comments-navigation'
import CommentsPageList from '../comments-page-list'

import { itemsCountSelector } from '../../selectors/comments'

function CommentsPage({ match, hasNext }) {
const page = match.params.page || 1
return (
<div>
<CommentsPageList page={page} />
<CommentsNavigation activePage={+page} hasNext={hasNext} />
</div>
)
}

function mapStateToProps(state, ownProps) {
const totalPagesCount = Math.ceil(itemsCountSelector(state) / 5)

return {
hasNext: totalPagesCount > (+ownProps.match.params.page || 1)
}
}

export default connect(mapStateToProps)(CommentsPage)
2 changes: 2 additions & 0 deletions src/constants/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ export const LOAD_ALL_ARTICLES = 'LOAD_ALL_ARTICLES'
export const LOAD_ARTICLE = 'LOAD_ARTICLE'
export const LOAD_ARTICLE_COMMENTS = 'LOAD_ARTICLE_COMMENTS'

export const LOAD_COMMENTS = 'LOAD_COMMENTS'

export const CHANGE_SELECTION = 'CHANGE_SELECTION'
export const CHANGE_DATE_RANGE = 'CHANGE_DATE_RANGE'

Expand Down
33 changes: 33 additions & 0 deletions src/reducer/all-comments.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import { OrderedMap, Record } from 'immutable'
import { LOAD_COMMENTS, SUCCESS } from '../constants/index'

import { arrToMap } from './utils'

const ReducerState = Record({
entities: new OrderedMap({}),
itemsCount: 0,
loading: false,
loaded: false,
error: null
})

const CommentRecord = Record({
id: null,
user: null,
text: null
})

export default (state = new ReducerState(), action) => {
switch (action.type) {
case LOAD_COMMENTS + SUCCESS:
return state
.setIn(
['entities', action.payload.page],
action.response.records.map((item) => new CommentRecord(item))
Copy link
Owner

Choose a reason for hiding this comment

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

я бы хранил комменты в comments.entities, по сути это те же сущности

)
.set('itemsCount', action.response.total)

default:
return state
}
}
4 changes: 3 additions & 1 deletion src/reducer/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,13 @@ import { combineReducers } from 'redux'
import counterReducer from './counter'
import articles from './articles'
import comments from './comments'
import allComments from './all-comments'
import filters from './filters'

export default combineReducers({
counter: counterReducer,
articles,
comments,
filters
filters,
allComments
})
11 changes: 11 additions & 0 deletions src/selectors/comments.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import { createSelector } from 'reselect'

const pageSelector = (_, props) => +props.page
export const commentsByPageCommonSelector = (state) => state.allComments.entities
export const itemsCountSelector = (state) => state.allComments.itemsCount

export const commentsByPageSelector = createSelector(
commentsByPageCommonSelector,
pageSelector,
(commentsByPage, page) => commentsByPage.get(page)
)