forked from sheepzh/time-tracker-4-browser
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathuseScrollRequest.ts
More file actions
69 lines (61 loc) · 1.76 KB
/
useScrollRequest.ts
File metadata and controls
69 lines (61 loc) · 1.76 KB
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
import { onBeforeMount, ref, type Ref, watch, type WatchSource } from "vue"
type Option<T> = {
manual?: boolean
defaultValue?: T[]
pageSize?: number
resetDeps?: WatchSource<unknown> | WatchSource<unknown>[]
}
type Result<T> = {
data: Ref<T[]>
end: Ref<boolean>
loading: Ref<boolean>
loadMore: () => void
loadMoreAsync: () => Promise<void>
reset: () => void
}
export const useScrollRequest = <T>(getter: (pageNo: number, pageSize: number) => Promise<T[]>, option?: Option<T>): Result<T> => {
const {
defaultValue,
manual,
pageSize: outerPageSize,
resetDeps,
} = option || {}
const data = ref<T[]>(defaultValue ?? []) as Ref<T[]>
const end = ref(false)
const loading = ref(false)
const pageNo = ref(0)
const pageSize = outerPageSize || 10
const loadMoreAsync = async () => {
if (end.value) return
try {
loading.value = true
const no = pageNo.value = (pageNo.value + 1)
const newData = await getter?.(no, pageSize) || []
data.value = [...(data.value || []), ...(newData || [])]
const newLen = newData?.length ?? 0
if (!newLen || newLen < pageSize) {
end.value = true
}
} finally {
loading.value = false
}
}
const reset = async () => {
end.value = false
pageNo.value = 0
data.value = []
await loadMoreAsync()
}
!manual && onBeforeMount(loadMoreAsync)
if (resetDeps && (!Array.isArray(resetDeps) || resetDeps?.length)) {
watch(resetDeps, reset)
}
return {
data,
end,
loading,
loadMore: () => loadMoreAsync(),
loadMoreAsync,
reset,
}
}