fix pagination errors

This commit is contained in:
Nuwan 2021-12-23 15:58:53 +05:30
parent edab0fe9fc
commit d35778f5e2
5 changed files with 508 additions and 107 deletions

View File

@ -1,6 +1,6 @@
import React, { useState, useEffect, useRef } from 'react';
import PropTypes from 'prop-types';
import { Alert, Card, CardBody, Col, Row, Button, Form } from 'reactstrap';
import { Alert, Col, Row } from 'reactstrap';
import Loader from '../common/Loader';
import { isIterableArray } from '../../helpers/utils';
import { useSelector } from 'react-redux';
@ -20,28 +20,6 @@ const JKPeople = ({ className, onPageChange }) => {
const { greaterThan } = useResponsive();
// const loadPeople = React.useCallback(() => {
// if (totalPages !== 0 && page > totalPages) {
// setPage(totalPages + 1);
// return;
// }
// try {
// onPageChange(page)
// } catch (error) {
// console.log('Error fetching people', error);
// }
// }, [page, totalPages, dispatch]);
// useEffect(() => {
// loadPeople();
// }, [page]);
// useEffect(() => {
// if (loadingStatus === 'succeeded' && peopleListRef.current && page !== 1) {
// }
// }, [loadingStatus]);
useEffect(() => {
try {
console.log("DEBUG======", page, hasNext);
@ -66,19 +44,6 @@ const JKPeople = ({ className, onPageChange }) => {
}
};
// const handleScroll = () => {
// if (window.innerHeight + window.scrollY >= document.body.offsetHeight) {
// goNextPage();
// }
// };
// useEffect(() => {
// window.addEventListener('scroll', handleScroll, { passive: true });
// return () => {
// window.removeEventListener('scroll', handleScroll);
// };
// }, []);
return (
<div>
{loadingStatus === 'loading' && people.length === 0 ? (

View File

@ -1,25 +1,38 @@
import React, { useState, useEffect, useRef } from 'react';
import { Button, Card, CardBody, Form, Modal, ModalHeader, ModalBody, ModalFooter } from 'reactstrap';
import { Alert, Col, Row, Button, Card, CardBody, Form, Modal, ModalHeader, ModalBody, ModalFooter } from 'reactstrap';
import FalconCardHeader from '../common/FalconCardHeader';
import Loader from '../common/Loader';
import { isIterableArray } from '../../helpers/utils';
import { useResponsive } from '@farfetch/react-context-responsive';
import { useTranslation } from 'react-i18next';
import Select from 'react-select';
import JKTooltip from '../common/JKTooltip';
import JKPeopleList from './JKPeopleList';
import JKPeopleSwiper from './JKPeopleSwiper';
import { getGenres, getInstruments } from '../../helpers/rest';
import { useForm, Controller, useFormState } from 'react-hook-form';
import { useDispatch, useSelector } from 'react-redux';
import { fetchPeople, resetState, loadPrefetched, preFetchPeople } from '../../store/features/peopleSlice';
import JKPeople from './JKPeople';
function JKPeopleFilter() {
const { t } = useTranslation();
const [ show, setShow ] = useState(false);
const [show, setShow] = useState(false);
const [resetFilter, setResetFilter] = useState(false);
const [instruments, setInstruments] = useState([]);
const [genres, setGenres] = useState([]);
const dispatch = useDispatch();
const pageToRequest = useRef(1)
const currentPage = useRef(1);
const nextPage = useRef(1);
const [hasNextPage, setHasNextPage] = useState(true)
const { greaterThan } = useResponsive();
const peopleListRef = useRef();
const people = useSelector(state => state.people.people);
const totalPages = useSelector(state => state.people.totalPages);
const loadingStatus = useSelector(state => state.people.status);
const { register, handleSubmit, setValue, control } = useForm({
defaultValues: {
@ -40,6 +53,22 @@ function JKPeopleFilter() {
const toggle = () => setShow(!show);
const lastActiveOpts = [
{ value: '', label: 'Any Range' },
{ value: '1', label: 'Within Last 1 Days' },
{ value: '7', label: 'Within Last 7 Days' },
{ value: '30', label: 'Within Last 30 Days' },
{ value: '90', label: 'Within Last 90 Days' }
];
const joinedOpts = [
{ value: '', label: 'Any Range' },
{ value: '1', label: 'Within Last 1 Days' },
{ value: '7', label: 'Within Last 7 Days' },
{ value: '30', label: 'Within Last 30 Days' },
{ value: '90', label: 'Within Last 90 Days' }
];
const fetchInstruments = async () => {
await getInstruments()
.then(response => {
@ -82,50 +111,37 @@ function JKPeopleFilter() {
});
};
useEffect(() => {
if (resetFilter) {
clearFilterOpts();
setResetFilter(false);
dispatch(resetState());
pageToRequest.current = 1
handleSubmit(onSubmit)()
}
}, [resetFilter]);
const goNextPage = () => {
submitPageQuery(currentPage.current)
};
const clearFilterOpts = () => {
setValue('latency_good', true)
setValue('latency_fair', true)
setValue('latency_high', false)
setValue('proficiency_beginner', true)
setValue('proficiency_intermediate', true)
setValue('proficiency_expert', true)
setValue('instruments', null)
setValue('genres', null)
setValue('joined_within_days', -1)
setValue('active_within_days', -1)
}
setValue('latency_good', true);
setValue('latency_fair', true);
setValue('latency_high', false);
setValue('proficiency_beginner', true);
setValue('proficiency_intermediate', true);
setValue('proficiency_expert', true);
setValue('instruments', null);
setValue('genres', null);
setValue('joined_within_days', -1);
setValue('active_within_days', -1);
};
useEffect(() => {
fetchGenres();
fetchInstruments();
}, []);
const submitPageQuery = () => {
handleSubmit(onSubmit)();
};
const submitForm = event => {
event.preventDefault();
pageToRequest.current = 1
currentPage.current = 1;
nextPage.current = 1;
dispatch(resetState());
handleSubmit(onSubmit)(pageToRequest.current);
handleSubmit(onSubmit)(nextPage.current);
setShow(false);
};
const submitPageQuery = (page, hasNextPage) => {
handleSubmit(onSubmit)(page, hasNextPage)
}
const onSubmit = (data, page, hasNextPage = true) => {
let _page = pageToRequest.current > page ? pageToRequest.current : page
const onSubmit = (data) => {
let genres = [];
let joined_within_days = '';
let active_within_days = '';
@ -133,48 +149,55 @@ function JKPeopleFilter() {
if (data.genres) {
genres = data.genres.map(genre => genre.value);
}
if(data.joined_within_days){
if (data.joined_within_days) {
joined_within_days = data.joined_within_days.value;
}
if(data.active_within_days){
if (data.active_within_days) {
active_within_days = data.active_within_days.value;
}
const params = { ...data, genres, joined_within_days, active_within_days };
try {
dispatch(loadPrefetched())
if(totalPages && _page > totalPages){
return
}
dispatch(fetchPeople({ data: params, page: _page }));
pageToRequest.current++
if(hasNextPage){
dispatch(preFetchPeople({ data: params, page: _page + 1 }))
pageToRequest.current = pageToRequest.current + 2
}
dispatch(loadPrefetched());
currentPage.current = nextPage.current
dispatch(fetchPeople({ data: params, page: currentPage.current }));
nextPage.current = currentPage.current + 1
if (hasNextPage) {
dispatch(preFetchPeople({ data: params, page: nextPage.current }));
nextPage.current = nextPage.current + 1;
}
} catch (error) {
console.log('error fetching people', error);
}
};
const lastActiveOpts = [
{ value: '', label: 'Any Range' },
{ value: '1', label: 'Within Last 1 Days' },
{ value: '7', label: 'Within Last 7 Days' },
{ value: '30', label: 'Within Last 30 Days' },
{ value: '90', label: 'Within Last 90 Days' }
];
useEffect(() => {
fetchGenres();
fetchInstruments();
submitPageQuery(currentPage.current)
}, []);
const joinedOpts = [
{ value: '', label: 'Any Range' },
{ value: '1', label: 'Within Last 1 Days' },
{ value: '7', label: 'Within Last 7 Days' },
{ value: '30', label: 'Within Last 30 Days' },
{ value: '90', label: 'Within Last 90 Days' }
];
useEffect(() => {
if(totalPages > 0){
setHasNextPage(currentPage.current < totalPages)
}
}, [totalPages, currentPage.current]);
useEffect(() => {
if (resetFilter) {
clearFilterOpts();
dispatch(resetState());
currentPage.current = 1;
nextPage.current = 1;
handleSubmit(onSubmit)();
setResetFilter(false);
}
}, [resetFilter]);
return (
<Card>
@ -193,7 +216,7 @@ function JKPeopleFilter() {
color="secondary"
className="fs--1"
data-testid="btnResetSearch"
onClick={() => setResetFilter(true) }
onClick={() => setResetFilter(true)}
>
{t('reset_filters', { ns: 'people' })}
</Button>
@ -359,8 +382,43 @@ function JKPeopleFilter() {
</Button>
</ModalFooter>
</Modal>
<JKPeople onPageChange={submitPageQuery} />
<div>
{loadingStatus === 'loading' && people.length === 0 ? (
<Loader />
) : isIterableArray(people) ? (
//Start Find Friends table hidden on small screens
<>
{greaterThan.xs ? (
<Row className="mb-3 justify-content-between d-none d-md-block">
<div className="table-responsive-xl px-2" ref={peopleListRef}>
<JKPeopleList
people={people}
goNextPage={goNextPage}
hasNext={hasNextPage}
isLoading={loadingStatus === 'loading' && people.length !== 0}
/>
</div>
</Row>
) : (
<Row className="swiper-container d-block d-md-none" data-testid="peopleSwiper">
<JKPeopleSwiper
people={people}
goNextPage={goNextPage}
/>
</Row>
)}
</>
) : (
<Row className="p-card">
<Col>
<Alert color="info" className="mb-0">
No Records!
</Alert>
</Col>
</Row>
)}
</div>
</CardBody>
</Card>
);

View File

@ -0,0 +1,372 @@
import React, { useState, useEffect, useRef } from 'react';
import { Button, Card, CardBody, Form, Modal, ModalHeader, ModalBody, ModalFooter } from 'reactstrap';
import FalconCardHeader from '../common/FalconCardHeader';
import { useTranslation } from 'react-i18next';
import Select from 'react-select';
import JKTooltip from '../common/JKTooltip';
import { getGenres, getInstruments } from '../../helpers/rest';
import { useForm, Controller, useFormState } from 'react-hook-form';
import { useDispatch, useSelector } from 'react-redux';
import { fetchPeople, resetState, loadPrefetched, preFetchPeople } from '../../store/features/peopleSlice';
import JKPeople from './JKPeople';
function JKPeopleFilter() {
const { t } = useTranslation();
const [ show, setShow ] = useState(false);
const [resetFilter, setResetFilter] = useState(false);
const [instruments, setInstruments] = useState([]);
const [genres, setGenres] = useState([]);
const dispatch = useDispatch();
const pageToRequest = useRef(1)
const totalPages = useSelector(state => state.people.totalPages);
const { register, handleSubmit, setValue, control } = useForm({
defaultValues: {
latency_good: true,
latency_fair: true,
latency_high: false,
proficiency_beginner: true,
proficiency_intermediate: true,
proficiency_expert: true,
instruments: [],
genres: [],
joined_within_days: '-1',
active_within_days: '-1'
}
});
const { isDirty } = useFormState({ control });
const toggle = () => setShow(!show);
const fetchInstruments = async () => {
await getInstruments()
.then(response => {
if (response.ok) {
return response.json();
}
})
.then(data => {
setInstruments(
data.map(instrument => {
return {
value: instrument.id,
label: instrument.description
};
})
);
})
.catch(error => console.log(error));
};
const fetchGenres = async () => {
await getGenres()
.then(response => {
if (response.ok) {
return response.json();
}
})
.then(data => {
setGenres(
data.map(genre => {
return {
value: genre.id,
label: genre.description
};
})
);
})
.catch(error => {
console.log(error);
});
};
useEffect(() => {
if (resetFilter) {
clearFilterOpts();
setResetFilter(false);
dispatch(resetState());
pageToRequest.current = 1
handleSubmit(onSubmit)()
}
}, [resetFilter]);
const clearFilterOpts = () => {
setValue('latency_good', true)
setValue('latency_fair', true)
setValue('latency_high', false)
setValue('proficiency_beginner', true)
setValue('proficiency_intermediate', true)
setValue('proficiency_expert', true)
setValue('instruments', null)
setValue('genres', null)
setValue('joined_within_days', -1)
setValue('active_within_days', -1)
}
useEffect(() => {
fetchGenres();
fetchInstruments();
}, []);
const submitForm = event => {
event.preventDefault();
pageToRequest.current = 1
dispatch(resetState());
handleSubmit(onSubmit)(pageToRequest.current);
setShow(false);
};
const submitPageQuery = (page, hasNextPage) => {
handleSubmit(onSubmit)(page, hasNextPage)
}
const onSubmit = (data, page, hasNextPage = true) => {
let _page = pageToRequest.current > page ? pageToRequest.current : page
let genres = [];
let joined_within_days = '';
let active_within_days = '';
if (data.genres) {
genres = data.genres.map(genre => genre.value);
}
if(data.joined_within_days){
joined_within_days = data.joined_within_days.value;
}
if(data.active_within_days){
active_within_days = data.active_within_days.value;
}
const params = { ...data, genres, joined_within_days, active_within_days };
console.log("---DEBUG--- _page", _page);
console.log("---DEBUG--- totalPages", totalPages);
try {
dispatch(loadPrefetched())
if(totalPages && _page > totalPages){
return
}
dispatch(fetchPeople({ data: params, page: _page }));
pageToRequest.current++
if(hasNextPage){
dispatch(preFetchPeople({ data: params, page: _page + 1 }))
pageToRequest.current = pageToRequest.current + 2
}
} catch (error) {
console.log('error fetching people', error);
}
};
const lastActiveOpts = [
{ value: '', label: 'Any Range' },
{ value: '1', label: 'Within Last 1 Days' },
{ value: '7', label: 'Within Last 7 Days' },
{ value: '30', label: 'Within Last 30 Days' },
{ value: '90', label: 'Within Last 90 Days' }
];
const joinedOpts = [
{ value: '', label: 'Any Range' },
{ value: '1', label: 'Within Last 1 Days' },
{ value: '7', label: 'Within Last 7 Days' },
{ value: '30', label: 'Within Last 30 Days' },
{ value: '90', label: 'Within Last 90 Days' }
];
return (
<Card>
<FalconCardHeader title={t('page_title', { ns: 'people' })} titleClass="font-weight-bold">
<Form inline className="mt-md-0 mt-3">
<Button
color="primary"
className="me-2 mr-2 fs--1"
onClick={() => setShow(true)}
data-testid="btnUpdateSearch"
>
{t('update_search', { ns: 'people' })}
</Button>
<Button
outline
color="secondary"
className="fs--1"
data-testid="btnResetSearch"
onClick={() => setResetFilter(true) }
>
{t('reset_filters', { ns: 'people' })}
</Button>
</Form>
</FalconCardHeader>
<CardBody className="pt-0">
<Modal
isOpen={show}
toggle={toggle}
className="mw-100 mx-1 mr-1 ml-1 mx-md-5 mr-md-5 ml-md-5 mx-xl-10 mr-xl-10 ml-xl-10"
data-testid="modalUpdateSearch"
>
<ModalHeader toggle={toggle}>Update Search</ModalHeader>
<ModalBody>
<div className="px-4 pb-4">
<form>
<div className="row justify-content-start mt-2">
{/* first column */}
<div className="col-12 col-md-6 mb-3 mb-md-0">
<div className="row justify-content-start">
<div className="col-6">
<label className="form-label">
Latency{' '}
<JKTooltip title="Use these checkboxes to search for other musicians by the estimated amount of latency between you and them. Latency is the amount of time it takes for each of your computers to process audio, plus the time it takes for this digital audio to move over the Internet between you." />
</label>
<div className="form-check">
<input
{...register('latency_good')}
type="checkbox"
className="form-check-input"
defaultChecked={!isDirty}
onChange={e => setValue('latency_good', e.target.checked)}
/>
<label className="form-check-label">Good (less than 40ms)</label>
</div>
<div className="form-check">
<input
{...register('latency_fair')}
type="checkbox"
className="form-check-input"
defaultChecked={!isDirty}
onChange={e => setValue('latency_fair', e.target.checked)}
/>
<label className="form-check-label">Fair (40-60ms)</label>
</div>
<div className="form-check">
<input
{...register('latency_high')}
type="checkbox"
className="form-check-input"
onChange={e => setValue('latency_high', e.target.checked)}
/>
<label className="form-check-label">Poor (more than 60ms)</label>
</div>
</div>
<div className="col-6">
<label className="form-label">
Skill Level{' '}
<JKTooltip title="Use these checkboxes to search for other musicians by their skill level." />
</label>
<div className="form-check">
<input
{...register('proficiency_beginner')}
type="checkbox"
className="form-check-input"
defaultChecked={!isDirty}
onChange={e => setValue('proficiency_beginner', e.target.checked)}
/>
<label className="form-check-label">Beginner</label>
</div>
<div className="form-check">
<input
{...register('proficiency_intermediate')}
type="checkbox"
className="form-check-input"
defaultChecked={!isDirty}
onChange={e => setValue('proficiency_intermediate', e.target.checked)}
/>
<label className="form-check-label">Intermediate</label>
</div>
<div className="form-check">
<input
{...register('proficiency_expert')}
type="checkbox"
className="form-check-input"
defaultChecked={!isDirty}
onChange={e => setValue('proficiency_expert', e.target.checked)}
/>
<label className="form-check-label">Expert</label>
</div>
</div>
</div>
</div>
{/* second column */}
<div className="col-12 col-md-6">
<label className="form-label" htmlFor="instruments">
Instruments{' '}
<JKTooltip title="Use these checkboxes to search for other musicians who play particular instruments. If you do not select any instruments, we search for any/all instruments. If you select multiple instruments, we search for musicians who play any of these instruments." />
</label>
<div className="choices">
<Controller
name="instruments"
control={control}
render={({ field }) => (
<Select
{...field}
options={instruments}
isMulti
closeMenuOnSelect={false}
id="selInstruments"
/>
)}
/>
</div>
<label className="form-label" htmlFor="genres">
Genres{' '}
<JKTooltip title="Use these checkboxes to search for other musicians who enjoy playing particular musical genres/styles. If you do not select any genres, we search for any/all genres. If you select multiple genres, we search for musicians who play any of these genres." />
</label>
<div className="choices">
<Controller
name="genres"
control={control}
render={({ field }) => (
<Select {...field} options={genres} isMulti closeMenuOnSelect={false} id="selGenres" />
)}
/>
</div>
<label className="form-label" htmlFor="lastActive">
Last Active{' '}
<JKTooltip title="Use this list to search for other musicians who have been active on JamKazam within a specified time period. More recent activity makes it more likely they will respond if you message or request to connect." />
</label>
<div className="choices">
<Controller
name="active_within_days"
control={control}
render={({ field }) => <Select {...field} options={lastActiveOpts} id="selLastActive" />}
/>
</div>
<label className="form-label" htmlFor="joined">
Joined JamKazam{' '}
<JKTooltip title="Use this list to search for other musicians based on when they joined JamKazam. This can be useful for finding and connecting with newer users." />
</label>
<div className="choices">
<Controller
name="joined_within_days"
control={control}
render={({ field }) => <Select {...field} options={joinedOpts} id="selJoinedWithin" />}
/>
</div>
</div>
</div>
</form>
</div>
</ModalBody>
<ModalFooter>
<Button color="outline-primary" onClick={toggle}>
Cancel
</Button>{' '}
<Button color="primary" onClick={submitForm} data-testid="btnSubmitSearch">
Search
</Button>
</ModalFooter>
</Modal>
<JKPeople onPageChange={submitPageQuery} />
</CardBody>
</Card>
);
}
export default JKPeopleFilter;

View File

@ -4,7 +4,7 @@ import JKPerson from './JKPerson';
import PropTypes from 'prop-types';
import { useTranslation } from 'react-i18next';
const JKPeopleList = ({ people, goNextPage, hasNext }) => {
const JKPeopleList = ({ people, goNextPage, hasNext, isLoading }) => {
const { t } = useTranslation();
return (
<>
@ -26,7 +26,12 @@ const JKPeopleList = ({ people, goNextPage, hasNext }) => {
))}
</tbody>
</Table>
{hasNext && <Button color="primary" outline={true} onClick={() => goNextPage()} data-testid="paginate-next-page">Load More</Button>}
{hasNext && (
<Button color="primary" outline={true} onClick={() => goNextPage()} data-testid="paginate-next-page">
{isLoading ? <span>Loading...</span> : <span>Load More</span>}
</Button>
)}
</>
);
};

View File

@ -157,7 +157,8 @@ class ApiSearchController < ApiController
filter_params.merge!(active_within_days: params[:active_within_days]) unless params[:active_within_days].blank?
sobj = MusicianSearch.user_search_filter(current_user)
@search = sobj.search_results_page(filter_params, [params[:page].to_i, 1].max, user_ids)
#@search = sobj.search_results_page(filter_params, [params[:page].to_i, 1].max, user_ids)
@search = sobj.search_results_page(filter_params, [params[:page].to_i, 1].max)
respond_with @search, responder: ApiResponder, status: 201, template: 'api_search/index'