-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathpanel-resources.tsx
66 lines (53 loc) · 1.72 KB
/
panel-resources.tsx
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
'use client'
import { useRef, useState } from 'react'
import { useParams } from 'next/navigation'
import { listResources, listResourcesBySlug } from '@/actions/resources'
import { Resource } from '@/types/resource'
import { NUMBER_OF_GENERATIONS_TO_FETCH } from '@/constants'
import { ListResource } from '@/components/list-resource'
import { LoadMore } from '@/components/load-more'
export function PanelResources({ resources }: { resources: Resource[] }) {
const isLastRequest = useRef(false)
const [data, setData] = useState<Resource[]>(resources)
const [hasResources, setHasResources] = useState(
resources.length > NUMBER_OF_GENERATIONS_TO_FETCH
)
const [isLoading, setIsLoading] = useState(false)
const params = useParams<{ slug: string }>()
const loadMoreResources = async () => {
if (isLastRequest.current || !data) return
let results: any = []
const from = data.length
const to = data.length + NUMBER_OF_GENERATIONS_TO_FETCH
setIsLoading(true)
if (params.slug === 'all' || Object.keys(params).length === 0) {
results = await listResources({
from,
to
})
} else {
const slug = params.slug
results = await listResourcesBySlug({
from,
to,
slug
})
}
setIsLoading(false)
if (!results) return
if (results.length > 0) {
setData((prevData) => prevData.concat(results))
}
// Hidding the load more button
if (results.length < NUMBER_OF_GENERATIONS_TO_FETCH + 1) {
isLastRequest.current = true
setHasResources(false)
}
}
return (
<>
<ListResource data={data} />
{hasResources && <LoadMore loadMoreResources={loadMoreResources} isLoading={isLoading} />}
</>
)
}