Skip to content

Commit

Permalink
feat(paginator): now loading posts on page change
Browse files Browse the repository at this point in the history
  • Loading branch information
Ali Obaji committed Sep 18, 2019
1 parent 926ed08 commit 3e0ecf7
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 6 deletions.
21 changes: 16 additions & 5 deletions pages/index.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import React, {useState} from 'react';
import React, {useEffect, useState} from 'react';
import './index.styles.css';
import {NextPage} from 'next';
import { useRouter } from 'next/router'

import {defaultMetaTags} from '../core/constants';
import Layout from '../shared/components/layout';
Expand Down Expand Up @@ -30,6 +31,7 @@ const IndexPage: NextPage = (props: Props) => {

const [skip, updateSkip] = useState(!!props.skip ? props.skip : 0);

const router = useRouter();
const page = !!props.page ? props.page : 1;
const entries = props.entries;
const tags = props.tags || [];
Expand All @@ -39,13 +41,17 @@ const IndexPage: NextPage = (props: Props) => {
const rangeLimit = Math.ceil(total / limit);
const range = calculateRange(rangeLimit);

useEffect(() => {
router.push({pathname: '/', query: {page: skip >= 0 ? skip : 0}});
}, [skip]);

return (
<Layout meta={defaultMetaTags}>
<div className="container">
<div className="blogposts">
<h1 className="blogposts__header">Latest posts</h1>
<div className="cards-deck">
{cards(posts)}
{cards(entries)}
</div>
</div>
<div className="sidenav">
Expand All @@ -62,9 +68,14 @@ const IndexPage: NextPage = (props: Props) => {
)
};

IndexPage.getInitialProps = async ({req, query}) => {
const {page} = query;
const {entries, total, skip, limit} = await getBlogPostEntries({limit: 1});
IndexPage.getInitialProps = async ({query}) => {

let page: number = 0;
if(parseInt(query.page + '') > 0) {
page = parseInt(query.page + '') - 1;
}

const {entries, total, skip, limit} = await getBlogPostEntries({limit: 1, skip: page});
const allTags = entries.map(entry => entry.tags);
const tags = Array.from(new Set(allTags.flat(1)));
return {page, entries, tags, total, skip, limit};
Expand Down
2 changes: 1 addition & 1 deletion shared/components/paginator/index.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import React, {FunctionComponent, Fragment, useState} from 'react';
import React, {FunctionComponent, Fragment, useState, useEffect} from 'react';
import './styles.css';
import {render} from "react-dom";

Expand Down

0 comments on commit 3e0ecf7

Please sign in to comment.