曹耘豪的博客

React之自定义获取数据hook - useDataLoader

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
import {useEffect, useState} from "react";

export default function useDataLoader<T>(loader: () => Promise<T> | undefined, deps: ReadonlyArray<unknown>) {
const [refreshState, setRefreshState] = useState(1)
const [loading, setLoading] = useState(true)
const [data, setData] = useState<T>()
const [lastUpdateTime, setLastUpdateTime] = useState(new Date())

useEffect(() => {
setLoading(true)
const r = loader();
if (r) {
r.then(data => {
setData(data)
setLastUpdateTime(new Date())
}).finally(() => {
setLoading(false)
})
} else {
setLoading(false)
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [refreshState, ...deps])

return {
loading,
data,
lastUpdateTime,
refresh: () => {
setRefreshState(refreshState + 1)
}
}
}
   /