Added article pagination

This commit is contained in:
Michael Fatemi 2020-11-25 19:07:13 -05:00
parent 4435307996
commit f5c0a4196e
3 changed files with 51 additions and 7 deletions

File diff suppressed because one or more lines are too long

3
.vscode/settings.json vendored Normal file
View File

@ -0,0 +1,3 @@
{
"typescript.tsdk": "node_modules\\typescript\\lib"
}

View File

@ -1,23 +1,64 @@
import React from 'react';
import useQuery from '../hooks/useInitiatives';
import ArticleRow from './ArticleRow';
import sanity from '../sanity';
export default function ArticleList() {
let articles = useQuery<SGA.ArticleDocument[]>(
'*[_type == "article"] | order(publish_date desc) [0...3]'
);
let [articles, setArticles] = React.useState<SGA.ArticleDocument[]>([]);
let [reachedEnd, setReachedEnd] = React.useState<boolean>(false);
// Fetch the next three articles
const addArticles = async (last_date: string, last_title: string) => {
const query = `*[_type == "article" && (
publish_date < $last_date ||
(
publish_date == $last_date &&
title > $last_title
)
)] | order(publish_date desc, title) [0...3]`;
const params = {
last_date,
last_title,
};
let articles = await sanity.fetch<SGA.ArticleDocument[]>(query, params);
console.log(articles.length);
if (articles.length < 3) {
setReachedEnd(true);
}
// Add the next articles
setArticles((oldArticles) => oldArticles.concat(articles));
};
React.useEffect(() => {
addArticles('3000-01-01', '');
}, []);
if (!articles) {
return null;
}
console.log(articles);
return (
<div style={{ display: 'flex', flexDirection: 'column' }}>
{articles.map((article) => {
return <ArticleRow key={article._id} article={article} />;
})}
{!reachedEnd ? (
<button
onClick={() => {
let lastArticle = articles[articles.length - 1];
addArticles(lastArticle.publish_date, lastArticle.title);
}}
>
Load more articles
</button>
) : (
<div>No more articles to show</div>
)}
</div>
);
}