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

Infinite Scrolling #3

Open
wants to merge 2 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
1 change: 1 addition & 0 deletions Gemfile
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ gem "omniauth-github"
gem 'omniauth-azure-activedirectory-v2'
gem 'faker'
gem 'activeadmin'
gem 'kaminari'

group :development, :test do
gem "debug", platforms: %i[ mri mingw x64_mingw ]
Expand Down
1 change: 1 addition & 0 deletions Gemfile.lock
Original file line number Diff line number Diff line change
Expand Up @@ -373,6 +373,7 @@ DEPENDENCIES
font-awesome-sass
jbuilder
jquery-rails
kaminari
omniauth
omniauth-azure-activedirectory-v2
omniauth-github
Expand Down
Binary file added app/assets/images/icons8-test-account-48.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
2 changes: 1 addition & 1 deletion app/assets/stylesheets/main.scss
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
.home-page {
height: calc(100vh - 130px);
height: calc(100vh - 132px);
}
.spinner {
position: absolute;
Expand Down
6 changes: 3 additions & 3 deletions app/controllers/api/v1/tweets_controller.rb
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,10 @@ class Api::V1::TweetsController < ApplicationController
before_action :authenticate_user!, except: [:index]

def index
@tweets = Tweet.all.ordered
@tweets = Tweet.all.ordered.page(params[:page]).per(ENV['PER_PAGE'])
respond_to do |format|
format.json do
render json: TweetSerializer.new(@tweets, is_login).serializable_hash.merge(is_login)
render json: TweetSerializer.new(@tweets).serializable_hash.merge(additional_params)
end
end
end
Expand Down Expand Up @@ -56,7 +56,7 @@ def set_current_user
Tweet.current_user = current_user
end

def is_login
def additional_params
{
is_login: current_user.present?
}
Expand Down
24 changes: 19 additions & 5 deletions app/javascript/api/apiTweets.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,23 @@ export const apiTweets = createApi({
tagTypes: ['Tweets'],
endpoints: (builder) => ({
getTweets: builder.query({
query: () => 'tweets.json',
query: ({page = 1}) => `tweets?page=${page}`,
serializeQueryArgs: ({ endpointName }) => {
return endpointName;
},
// Merge incoming data to the cache entry for scrolling page
merge: (currentCache, newItems, opts) => {
if (opts.arg.hasNextPage) {
currentCache.data.push(...newItems.data);
} else {
return { data: newItems.data }
}
},
// Refetch when the page arg changes
forceRefetch({ currentArg, previousArg }) {
return currentArg !== previousArg;
},
providesTags: ['Tweets'],
// headers: { 'Content-Type': 'multipart/form-data' }
}),
addTweet: builder.mutation({
query: (tweet) => ({
Expand All @@ -19,7 +33,7 @@ export const apiTweets = createApi({
body: tweet,
headers: { 'X-CSRF-Token': csrfToken },
}),
invalidatesTags: ['Tweets'],
invalidatesTags:['Tweets'],
}),
updateTweet: builder.mutation({
query: (tweet) => ({
Expand All @@ -28,7 +42,7 @@ export const apiTweets = createApi({
body: tweet,
headers: { 'X-CSRF-Token': csrfToken },
}),
invalidatesTags: ['Tweets'],
invalidatesTags:['Tweets'],
}),
removeTweet: builder.mutation({
query: (id) => ({
Expand All @@ -37,7 +51,7 @@ export const apiTweets = createApi({
body: id,
headers: { 'X-CSRF-Token': csrfToken },
}),
invalidatesTags: ['Tweets'],
invalidatesTags:['Tweets'],
}),
})
})
Expand Down
4 changes: 3 additions & 1 deletion app/javascript/components/Tweets/CreateTweetForm.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,13 @@ import Form from "react-bootstrap/Form";
import {Button} from "react-bootstrap";
import {useAddTweetMutation} from "../../api/apiTweets";

const CreateTweetForm = ({tweet, setTweet, onChangeTweet}) => {
const CreateTweetForm = ({tweet, setTweet, onChangeTweet, setPage, setHasNextPage}) => {
const [addTweet, { isSuccess }] = useAddTweetMutation()

const onClickSave = () => {
addTweet(tweet)
.then(setPage(1))
.then(setHasNextPage(false))
}
useEffect(() => {
isSuccess && setTweet('')
Expand Down
30 changes: 6 additions & 24 deletions app/javascript/components/Tweets/TweetItem.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,15 +4,14 @@ import {PencilSquare, Trash} from "react-bootstrap-icons";
import {sweetAlertRemoveTweet} from "../helpers/helpers";
import {useRemoveTweetMutation} from "../../api/apiTweets";
import EditTweetModal from "../modals/EditTweetModal";
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'
import { faCircleUser } from '@fortawesome/free-solid-svg-icons'
import userIcon from "../../../assets/images/icons8-test-account-48.png";

const TweetItem = ({tweet}) => {
const TweetItem = ({tweet, setHasNextPage, setPage}) => {
const [editTweet, setEditTweet] = useState(tweet)
const [showModal, setShowModal] = useState(false);
const [removeTweet] = useRemoveTweetMutation()
const removeTweetConfirm = () => {
sweetAlertRemoveTweet(tweet, removeTweet)
sweetAlertRemoveTweet(tweet, removeTweet, setHasNextPage, setPage)
}
const handleShowEdit = () => setShowModal(p => !p);
const onChangeEditTweet = (e) => {
Expand All @@ -23,7 +22,7 @@ const TweetItem = ({tweet}) => {
const AvatarBlock = () => {
return <div className="row">
<div className="col avatar mt-1">
<FontAwesomeIcon icon={faCircleUser} size="4x" />
<i className="me-2 text-dark"><img src={userIcon} alt={"icon"}/></i>
</div>
<div className="col">
<p className='align-text-top'>{email}</p><br/>
Expand All @@ -32,25 +31,6 @@ const TweetItem = ({tweet}) => {
</div>
}

const DropDown = () => {
return <div className="dropdown">
<button
className="btn btn-primary dropdown-toggle hidden-arrow"
type="button"
id="dropdownMenuButton1"
data-mdb-toggle="dropdown"
aria-expanded="false"
>
<i className="fas fa-ellipsis-v fa-lg"></i>
</button>
<ul className="dropdown-menu" aria-labelledby="dropdownMenuButton1">
<li><a className="dropdown-item" href="#"> <i className="fas fa-user-alt pe-2"></i>My Profile</a></li>
<li><a className="dropdown-item" href="#"> <i className="fas fa-cog pe-2"></i>Settings</a></li>
<li><a className="dropdown-item" href="#"> <i className="fas fa-door-open pe-2"></i>Logout</a></li>
</ul>
</div>
}

return <tr className="fw-normal">
<td className="align-middle">
<div className="card w-100">
Expand All @@ -75,6 +55,8 @@ const TweetItem = ({tweet}) => {
onChangeEditTweet={onChangeEditTweet}
showModal={showModal}
handleShowEdit={handleShowEdit}
setHasNextPage={setHasNextPage}
setPage={setPage}
/>

</td>
Expand Down
43 changes: 35 additions & 8 deletions app/javascript/components/Tweets/Tweets.jsx
Original file line number Diff line number Diff line change
@@ -1,18 +1,28 @@
import React, {useEffect, useState} from "react";
import React, {useEffect, useMemo, useState} from "react";
import {useGetTweetsQuery} from "../../api/apiTweets";
import Spinner from "../common/Spinner";
import CreateTweetForm from "./CreateTweetForm";
import TweetItem from "./TweetItem";
import { Waypoint } from 'react-waypoint';

const Tweets = () => {
const [tweet, setTweet] = useState({})
const [page, setPage] = useState(1);
const [isLogin, setIsLogin] = useState(false);
const [hasNextPage, setHasNextPage] = useState(false);
const {
data: tweets,
isLoading,
isSuccess,
isError,
error,
} = useGetTweetsQuery();
} = useGetTweetsQuery({page, hasNextPage});

useEffect(() => {
if (isLoading) return
isSuccess && setIsLogin(tweets.is_login)
}, [isLoading])

const onChangeTweet = (e) => {
setTweet(Object.assign({}, tweet, {[e.target.name]: e.target.value}))
}
Expand All @@ -25,24 +35,41 @@ const Tweets = () => {
return <div>{error.status}</div>;
}

const tweetItem = tweets.data.map((tweet) => {
return <TweetItem key={tweet.id} tweet={tweet.attributes} />
const tweetItem = tweets.data.map(tweet => {
return <TweetItem
key={tweet.id}
tweet={tweet.attributes}
setHasNextPage={setHasNextPage}
setPage={setPage}
/>
})

return isSuccess && <section className="home-page">
const onScrollDown = () => {
setHasNextPage(true)
setPage(page + 1)
}

return <section className="home-page">
<div className="container h-100">
<div className="row d-flex justify-content-center align-items-center h-100">
<div className="col-md-12 col-xl-10 h-100">
<div className="card h-100">
<div className="card-header p-3" hidden={!tweets.is_login}>
<CreateTweetForm tweet={tweet} setTweet={setTweet} onChangeTweet={onChangeTweet} />
<div className="card-header p-3" hidden={!isLogin}>
<CreateTweetForm
tweet={tweet}
setTweet={setTweet}
onChangeTweet={onChangeTweet}
setHasNextPage={setHasNextPage}
setPage={setPage}
/>
</div>
<div className="card-body table-scroll">
<table className="table mb-0">
<tbody>
{tweetItem}
</tbody>
</table>
<Waypoint onEnter={onScrollDown} />
</div>
</div>
</div>
Expand All @@ -51,4 +78,4 @@ const Tweets = () => {
</section>
}

export default Tweets
export default Tweets
6 changes: 4 additions & 2 deletions app/javascript/components/helpers/helpers.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import withReactContent from 'sweetalert2-react-content'

export const csrfToken = document.querySelector('[name=csrf-token]').content

export const sweetAlertRemoveTweet = (tweet, action) => {
export const sweetAlertRemoveTweet = (tweet, removeTweet, setHasNextPage, setPage) => {
const MySwal = withReactContent(Swal)
MySwal.fire({
title: `Are you sure you want to remove tweet?`,
Expand All @@ -14,7 +14,9 @@ export const sweetAlertRemoveTweet = (tweet, action) => {
confirmButtonText: 'Remove'
}).then((result) => {
if (result.isConfirmed) {
action(tweet.id)
removeTweet(tweet.id)
setHasNextPage(false)
setPage(1)
}
})
}
Expand Down
10 changes: 8 additions & 2 deletions app/javascript/components/modals/EditTweetModal.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,17 @@ import {Button} from "react-bootstrap";
import Modal from "react-bootstrap/Modal";
import {useUpdateTweetMutation} from "../../api/apiTweets";

const EditTweetModal = ({onChangeEditTweet, handleShowEdit, editTweet, showModal }) => {
const EditTweetModal = ({
onChangeEditTweet, handleShowEdit, editTweet, showModal,
setHasNextPage, setPage
}) => {
const [updateTweet] = useUpdateTweetMutation()

const onClickSave = () => {
updateTweet(editTweet).then(handleShowEdit())
updateTweet(editTweet)
.then(handleShowEdit())
.then(setHasNextPage(false))
.then(setPage(1))
}

return <Modal show={showModal} onHide={handleShowEdit} animation={false}>
Expand Down
2 changes: 2 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
"@popperjs/core": "^2.11.6",
"@rails/webpacker": "5.4.3",
"@reduxjs/toolkit": "^1.9.1",
"axios": "^1.2.3",
"babel-plugin-transform-react-remove-prop-types": "^0.4.24",
"bootstrap": "^5.2.3",
"bootstrap-icons": "^1.10.3",
Expand All @@ -26,6 +27,7 @@
"react-loader-spinner": "^5.3.4",
"react-redux": "^8.0.5",
"react-router-dom": "^6.6.2",
"react-waypoint": "^10.3.0",
"react_ujs": "^2.6.2",
"sass": "^1.57.1",
"style-loader": "^3.3.1",
Expand Down
Loading