forked from vercel/next.js
-
Notifications
You must be signed in to change notification settings - Fork 0
/
post-list.js
119 lines (113 loc) · 2.91 KB
/
post-list.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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
import { useState } from 'react'
import { useQuery } from 'graphql-hooks'
import ErrorMessage from './error-message'
import PostUpvoter from './post-upvoter'
import Submit from './submit'
export const allPostsQuery = `
query allPosts($first: Int!, $skip: Int!) {
allPosts(orderBy: createdAt_DESC, first: $first, skip: $skip) {
id
title
votes
url
createdAt
}
_allPostsMeta {
count
}
}
`
export const allPostsQueryOptions = (skip = 0) => ({
variables: { skip, first: 10 },
updateData: (prevResult, result) => ({
...result,
allPosts: prevResult
? [...prevResult.allPosts, ...result.allPosts]
: result.allPosts,
}),
})
export default function PostList() {
const [skip, setSkip] = useState(0)
const { loading, error, data, refetch } = useQuery(
allPostsQuery,
allPostsQueryOptions(skip)
)
if (error) return <ErrorMessage message="Error loading posts." />
if (!data) return <div>Loading</div>
const { allPosts, _allPostsMeta } = data
const areMorePosts = allPosts.length < _allPostsMeta.count
return (
<>
<Submit
onSubmission={() => {
refetch({ variables: { skip: 0, first: allPosts.length } })
}}
/>
<section>
<ul>
{allPosts.map((post, index) => (
<li key={post.id}>
<div>
<span>{index + 1}. </span>
<a href={post.url}>{post.title}</a>
<PostUpvoter
id={post.id}
votes={post.votes}
onUpdate={() => {
refetch({ variables: { skip: 0, first: allPosts.length } })
}}
/>
</div>
</li>
))}
</ul>
{areMorePosts ? (
<button onClick={() => setSkip(skip + 10)}>
{' '}
{loading && !data ? 'Loading...' : 'Show More'}{' '}
</button>
) : (
''
)}
<style jsx>{`
section {
padding-bottom: 20px;
}
li {
display: block;
margin-bottom: 10px;
}
div {
align-items: center;
display: flex;
}
a {
font-size: 14px;
margin-right: 10px;
text-decoration: none;
padding-bottom: 0;
border: 0;
}
span {
font-size: 14px;
margin-right: 5px;
}
ul {
margin: 0;
padding: 0;
}
button:before {
align-self: center;
border-style: solid;
border-width: 6px 4px 0 4px;
border-color: #ffffff transparent transparent transparent;
content: '';
height: 0;
margin-right: 5px;
width: 0;
}
`}</style>
</section>
</>
)
}