-
Notifications
You must be signed in to change notification settings - Fork 54
/
Copy pathblog.js
64 lines (56 loc) · 1.99 KB
/
blog.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
import React, { useEffect, useState } from 'react';
import styles from '../styles/Blog.module.css'
import Link from 'next/link';
import * as fs from 'fs';
import InfiniteScroll from 'react-infinite-scroll-component';
// Step 1: Collect all the files from blogdata directory
// Step 2: Iterate through the and Display them
const Blog = (props) => {
const [blogs, setBlogs] = useState(props.allBlogs);
const [count, setCount] = useState(2)
const fetchData = async () => {
let d = await fetch(`http://localhost:3000/api/blogs/?count=${count + 2}`)
setCount(count + 2)
let data = await d.json()
setBlogs(data)
};
return <div className={styles.container}>
<main className={styles.main}>
<InfiniteScroll
dataLength={blogs.length} //This is important field to render the next data
next={fetchData}
hasMore={props.allCount !== blogs.length}
loader={<h4>Loading...</h4>}
endMessage={
<p style={{ textAlign: 'center' }}>
<b>Yay! You have seen it all</b>
</p>
}
>
{blogs.map((blogitem) => {
return <div key={blogitem.slug}>
<Link href={`/blogpost/${blogitem.slug}`}>
<h3 className={styles.blogItemh3}>{blogitem.title}</h3></Link>
<p className={styles.blogItemp}>{blogitem.metadesc.substr(0, 140)}...</p>
<Link href={`/blogpost/${blogitem.slug}`}><button className={styles.btn}>Read More</button></Link>
</div>
})}
</InfiniteScroll>
</main>
</div>
};
export async function getStaticProps(context) {
let data = await fs.promises.readdir("blogdata");
let allCount = data.length;
let myfile;
let allBlogs = [];
for (let index = 0; index < 2; index++) {
const item = data[index];
myfile = await fs.promises.readFile(('blogdata/' + item), 'utf-8')
allBlogs.push(JSON.parse(myfile))
}
return {
props: { allBlogs, allCount }, // will be passed to the page component as props
}
}
export default Blog;