stacker.news/components/items.js

78 lines
2.0 KiB
JavaScript
Raw Normal View History

2021-04-22 22:14:32 +00:00
import { useQuery } from '@apollo/client'
2021-06-22 17:47:49 +00:00
import Button from 'react-bootstrap/Button'
2021-04-22 22:14:32 +00:00
import Item, { ItemSkeleton } from './item'
2021-04-14 23:56:29 +00:00
import styles from './items.module.css'
2021-06-22 17:47:49 +00:00
import { MORE_ITEMS } from '../fragments/items'
import { useState } from 'react'
import { useRouter } from 'next/router'
2021-04-14 23:56:29 +00:00
2021-06-22 17:47:49 +00:00
export default function Items ({ variables, rank }) {
const router = useRouter()
const { error, data, fetchMore } = useQuery(MORE_ITEMS, {
variables,
fetchPolicy: router.query.cache ? 'cache-first' : undefined
2021-06-22 17:47:49 +00:00
})
2021-04-22 22:14:32 +00:00
if (error) return <div>Failed to load!</div>
if (!data) {
2021-06-24 23:58:58 +00:00
return <ItemsSkeleton rank={rank} />
2021-06-22 17:47:49 +00:00
}
2021-04-22 22:14:32 +00:00
2021-06-22 17:47:49 +00:00
const { moreItems: { items, cursor } } = data
return (
<>
2021-04-22 22:14:32 +00:00
<div className={styles.grid}>
2021-06-22 17:47:49 +00:00
{items.map((item, i) => (
<Item item={item} rank={rank && i + 1} key={item.id} />
2021-04-22 22:14:32 +00:00
))}
</div>
2021-06-24 23:58:58 +00:00
<MoreFooter cursor={cursor} fetchMore={fetchMore} offset={items.length} rank={rank} />
2021-06-22 17:47:49 +00:00
</>
)
}
2021-06-24 23:58:58 +00:00
function ItemsSkeleton ({ rank, startRank = 0 }) {
2021-06-22 17:47:49 +00:00
const items = new Array(21).fill(null)
2021-04-22 22:14:32 +00:00
2021-04-14 23:56:29 +00:00
return (
<div className={styles.grid}>
2021-06-22 17:47:49 +00:00
{items.map((_, i) => (
2021-06-24 23:58:58 +00:00
<ItemSkeleton rank={rank && i + startRank + 1} key={i + startRank} />
2021-04-14 23:56:29 +00:00
))}
</div>
)
}
2021-06-22 17:47:49 +00:00
2021-06-24 23:58:58 +00:00
function MoreFooter ({ cursor, fetchMore, rank, offset }) {
2021-06-22 17:47:49 +00:00
const [loading, setLoading] = useState(false)
if (loading) {
2021-06-24 23:58:58 +00:00
return <ItemsSkeleton rank={rank} startRank={offset} />
2021-06-22 17:47:49 +00:00
}
let Footer
if (cursor) {
Footer = () => (
<Button
2021-06-24 23:56:01 +00:00
variant='primary'
size='md'
2021-06-22 17:47:49 +00:00
onClick={async () => {
setLoading(true)
await fetchMore({
variables: {
cursor
}
})
setLoading(false)
}}
2021-06-24 23:56:01 +00:00
>more
2021-06-22 17:47:49 +00:00
</Button>
)
} else {
Footer = () => (
<div className='text-muted' style={{ fontFamily: 'lightning', fontSize: '2rem', opacity: '0.6' }}>GENISIS</div>
)
}
return <div className='d-flex justify-content-center mt-4 mb-2'><Footer /></div>
}