-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathindex.ts
38 lines (33 loc) · 790 Bytes
/
index.ts
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
import { useRef } from 'react'
const castArray = (value) => {
if (value == null) {
return []
}
if (Array.isArray(value)) {
return value
}
return [value]
}
type Noop = (...args: any[]) => any
const noop: Noop = () => {}
// @ts-ignore
function usePersistFn<T extends Noop>(fn?: T = noop, decorates: (fn: T) => T | Array<(fn: T) => T> = []): T {
const fnRef = useRef<T>(fn)
fnRef.current = fn
const persistFn = useRef<T>()
if (!persistFn.current) {
persistFn.current = (castArray(decorates) || []).reduce(
(acc, fn) => {
if (fn) {
return fn(acc)
}
return acc
},
function (...args) {
return fnRef.current?.apply(this, args)
}
)
}
return persistFn.current
}
export default usePersistFn