Add infinite scroll to post list

This commit is contained in:
riggraz
2019-09-04 21:12:07 +02:00
parent 2a42d3069c
commit f9f2b291d6
8 changed files with 98 additions and 27 deletions

View File

@@ -37,6 +37,9 @@ gem "administrate", git: "https://github.com/thoughtbot/administrate.git"
# React # React
gem 'react-rails' gem 'react-rails'
# Pagination
gem 'kaminari'
group :development, :test do group :development, :test do
# Call 'byebug' anywhere in the code to stop execution and get a debugger console # Call 'byebug' anywhere in the code to stop execution and get a debugger console
gem 'byebug', platforms: [:mri, :mingw, :x64_mingw] gem 'byebug', platforms: [:mri, :mingw, :x64_mingw]

View File

@@ -309,6 +309,7 @@ DEPENDENCIES
devise! devise!
factory_bot_rails factory_bot_rails
jbuilder (~> 2.7) jbuilder (~> 2.7)
kaminari
listen (>= 3.0.5, < 3.2) listen (>= 3.0.5, < 3.2)
pg (>= 0.18, < 2.0) pg (>= 0.18, < 2.0)
puma (~> 3.11) puma (~> 3.11)

View File

@@ -6,6 +6,7 @@ class PostsController < ApplicationController
.left_outer_joins(:post_status) .left_outer_joins(:post_status)
.select('posts.title, posts.description, post_statuses.name as post_status_name, post_statuses.color as post_status_color') .select('posts.title, posts.description, post_statuses.name as post_status_name, post_statuses.color as post_status_color')
.where(filter_params) .where(filter_params)
.page(params[:page])
render json: posts render json: posts
end end
@@ -25,11 +26,12 @@ class PostsController < ApplicationController
private private
def filter_params def filter_params
defaults = { board_id: Board.first.id } defaults = { board_id: Board.first.id, page: 1 }
params params
.permit(:board_id, :post_status_id) .permit(:board_id, :post_status_id, :page)
.with_defaults(defaults) .with_defaults(defaults)
.except(:page) # do not return page param
end end
def post_params def post_params

View File

@@ -1,5 +1,7 @@
import * as React from 'react'; import * as React from 'react';
import InfiniteScroll from 'react-infinite-scroller';
import PostListItem from './PostListItem'; import PostListItem from './PostListItem';
import Spinner from '../shared/Spinner'; import Spinner from '../shared/Spinner';
@@ -9,14 +11,24 @@ interface Props {
posts: Array<IPost>; posts: Array<IPost>;
areLoading: boolean; areLoading: boolean;
error: string; error: string;
handleLoadMore(): void;
page: number;
hasMore: boolean;
} }
const PostList = ({ posts, areLoading, error }: Props) => ( const PostList = ({ posts, areLoading, error, handleLoadMore, page, hasMore }: Props) => (
<div className="box postList"> <div className="box postList">
{ areLoading ? <Spinner /> : null }
{ error ? <span className="error">{error}</span> : null } { error ? <span className="error">{error}</span> : null }
{ <InfiniteScroll
posts.map((post, i) => ( initialLoad={false}
loadMore={handleLoadMore}
threshold={50}
hasMore={hasMore}
loader={<Spinner />}
useWindow={true}
>
{posts.map((post, i) => (
<PostListItem <PostListItem
title={post.title} title={post.title}
description={post.description} description={post.description}
@@ -24,8 +36,8 @@ const PostList = ({ posts, areLoading, error }: Props) => (
key={i} key={i}
/> />
)) ))}
} </InfiniteScroll>
</div> </div>
); );

View File

@@ -24,6 +24,9 @@ interface State {
items: Array<IPost>; items: Array<IPost>;
areLoading: boolean; areLoading: boolean;
error: string; error: string;
page: number;
hasMore: boolean;
}; };
postStatuses: { postStatuses: {
items: Array<IPostStatus>; items: Array<IPostStatus>;
@@ -42,19 +45,24 @@ class Board extends React.Component<Props, State> {
}, },
posts: { posts: {
items: [], items: [],
areLoading: true, areLoading: false,
error: '', error: '',
page: 0,
hasMore: true,
}, },
postStatuses: { postStatuses: {
items: [], items: [],
areLoading: true, areLoading: false,
error: '', error: '',
} }
}; };
this.requestPosts = this.requestPosts.bind(this); this.requestPosts = this.requestPosts.bind(this);
this.loadMorePosts = this.loadMorePosts.bind(this);
this.requestPostStatuses = this.requestPostStatuses.bind(this); this.requestPostStatuses = this.requestPostStatuses.bind(this);
this.setPostStatusFilter = this.setPostStatusFilter.bind(this); this.setPostStatusFilter = this.setPostStatusFilter.bind(this);
} }
componentDidMount() { componentDidMount() {
@@ -62,7 +70,13 @@ class Board extends React.Component<Props, State> {
this.requestPostStatuses(); this.requestPostStatuses();
} }
async requestPosts() { loadMorePosts() {
this.requestPosts(this.state.posts.page + 1);
}
async requestPosts(page = 1) {
if (this.state.posts.areLoading) return;
this.setState({ this.setState({
posts: { ...this.state.posts, areLoading: true }, posts: { ...this.state.posts, areLoading: true },
}); });
@@ -71,26 +85,51 @@ class Board extends React.Component<Props, State> {
const { byPostStatus } = this.state.filters; const { byPostStatus } = this.state.filters;
let params = ''; let params = '';
params += `page=${page}`;
params += `&board_id=${boardId}`;
if (byPostStatus) params += `&post_status_id=${byPostStatus}`; if (byPostStatus) params += `&post_status_id=${byPostStatus}`;
try { try {
let res = await fetch(`/posts?board_id=${boardId}${params}`); let res = await fetch(`/posts?${params}`);
let data = await res.json(); let data = await res.json();
this.setState({ if (page === 1) {
posts: { this.setState({
items: data.map(post => ({ posts: {
title: post.title, items: data.map(post => ({
description: post.description, title: post.title,
postStatus: { description: post.description,
name: post.post_status_name, postStatus: {
color: post.post_status_color, name: post.post_status_name,
}, color: post.post_status_color,
})), },
areLoading: false, })),
error: '', areLoading: false,
} error: '',
}); page,
hasMore: data.length === 15,
}
});
} else {
this.setState({
posts: {
items: [...this.state.posts.items, ...data.map(post => ({
title: post.title,
description: post.description,
postStatus: {
name: post.post_status_name,
color: post.post_status_color,
},
}))],
areLoading: false,
error: '',
page,
hasMore: data.length === 15,
}
});
}
} catch (e) { } catch (e) {
this.setState({ this.setState({
posts: { ...this.state.posts, error: 'An unknown error occurred, try again.' }, posts: { ...this.state.posts, error: 'An unknown error occurred, try again.' },
@@ -156,6 +195,10 @@ class Board extends React.Component<Props, State> {
posts={posts.items} posts={posts.items}
areLoading={posts.areLoading} areLoading={posts.areLoading}
error={posts.error} error={posts.error}
handleLoadMore={this.loadMorePosts}
page={posts.page}
hasMore={posts.hasMore}
/> />
</div> </div>
); );

View File

@@ -4,4 +4,6 @@ class Post < ApplicationRecord
belongs_to :post_status, optional: true belongs_to :post_status, optional: true
validates :title, presence: true, length: { in: 4..64 } validates :title, presence: true, length: { in: 4..64 }
paginates_per 15
end end

View File

@@ -16,6 +16,7 @@
"prop-types": "^15.7.2", "prop-types": "^15.7.2",
"react": "^16.9.0", "react": "^16.9.0",
"react-dom": "^16.9.0", "react-dom": "^16.9.0",
"react-infinite-scroller": "^1.2.4",
"react_ujs": "^2.6.0", "react_ujs": "^2.6.0",
"ts-loader": "^6.0.4", "ts-loader": "^6.0.4",
"turbolinks": "^5.2.0", "turbolinks": "^5.2.0",

View File

@@ -5633,7 +5633,7 @@ promise-inflight@^1.0.1:
resolved "https://registry.yarnpkg.com/promise-inflight/-/promise-inflight-1.0.1.tgz#98472870bf228132fcbdd868129bad12c3c029e3" resolved "https://registry.yarnpkg.com/promise-inflight/-/promise-inflight-1.0.1.tgz#98472870bf228132fcbdd868129bad12c3c029e3"
integrity sha1-mEcocL8igTL8vdhoEputEsPAKeM= integrity sha1-mEcocL8igTL8vdhoEputEsPAKeM=
prop-types@^15.6.2, prop-types@^15.7.2: prop-types@^15.5.8, prop-types@^15.6.2, prop-types@^15.7.2:
version "15.7.2" version "15.7.2"
resolved "https://registry.yarnpkg.com/prop-types/-/prop-types-15.7.2.tgz#52c41e75b8c87e72b9d9360e0206b99dcbffa6c5" resolved "https://registry.yarnpkg.com/prop-types/-/prop-types-15.7.2.tgz#52c41e75b8c87e72b9d9360e0206b99dcbffa6c5"
integrity sha512-8QQikdH7//R2vurIJSutZ1smHYTcLpRWEOlHnzcWHmBYrOGUysKwSsrC89BCiFj3CbrfJ/nXFdJepOVrY1GCHQ== integrity sha512-8QQikdH7//R2vurIJSutZ1smHYTcLpRWEOlHnzcWHmBYrOGUysKwSsrC89BCiFj3CbrfJ/nXFdJepOVrY1GCHQ==
@@ -5805,6 +5805,13 @@ react-dom@^16.9.0:
prop-types "^15.6.2" prop-types "^15.6.2"
scheduler "^0.15.0" scheduler "^0.15.0"
react-infinite-scroller@^1.2.4:
version "1.2.4"
resolved "https://registry.yarnpkg.com/react-infinite-scroller/-/react-infinite-scroller-1.2.4.tgz#f67eaec4940a4ce6417bebdd6e3433bfc38826e9"
integrity sha512-/oOa0QhZjXPqaD6sictN2edFMsd3kkMiE19Vcz5JDgHpzEJVqYcmq+V3mkwO88087kvKGe1URNksHEOt839Ubw==
dependencies:
prop-types "^15.5.8"
react-is@^16.8.1: react-is@^16.8.1:
version "16.9.0" version "16.9.0"
resolved "https://registry.yarnpkg.com/react-is/-/react-is-16.9.0.tgz#21ca9561399aad0ff1a7701c01683e8ca981edcb" resolved "https://registry.yarnpkg.com/react-is/-/react-is-16.9.0.tgz#21ca9561399aad0ff1a7701c01683e8ca981edcb"