-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathuseFilter.ts
97 lines (81 loc) · 1.98 KB
/
useFilter.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
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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
import { useReducer, type Reducer, useMemo } from 'react'
interface DataFilter<T> {
(text: string): T
}
export type FilterActions = {
onFilterStart: () => void
onReset: () => void
onChange: (text: string) => void
}
export type UseFilterResult<T> = {
data: null | T
manager: FilterActions & { isFiltering: boolean }
}
export type FilterState<T> = {
isLoading: boolean
text: string
data: null | T
}
type StartFilterAction = {
type: 'start'
}
type ChangeFilterAction<T> = {
type: 'change'
text: string
data: T
}
type ResetFilterAction = {
type: 'reset'
}
type RequestAction<T> = StartFilterAction | ChangeFilterAction<T> | ResetFilterAction
function filterReducer<T>(state: FilterState<T>, action: RequestAction<T>): FilterState<T> {
switch (action.type) {
case 'start':
return {
...state,
isLoading: true
}
case 'change':
return {
isLoading: false,
text: action.text,
data: action.data,
}
case 'reset':
return initialFilterState
}
}
function noop() {}
export const noopFilterActions: FilterActions = {
onFilterStart: noop,
onChange: noop,
onReset: noop,
}
export const initialFilterState = {
isLoading: false,
text: '',
data: null,
}
export function useFilter<T>(fn: DataFilter<T>): UseFilterResult<T> {
const [state, dispatch] = useReducer<Reducer<FilterState<T>, RequestAction<T>>>(
filterReducer,
initialFilterState,
)
const manager = useMemo(() => ({
isFiltering: state.isLoading,
onFilterStart: () => {
dispatch({ type: 'start' })
},
onChange: (text: string) => {
const data = fn(text)
dispatch({ type: 'change', text, data })
},
onReset: () => {
dispatch({ type: 'reset' })
},
}), [fn, state.isLoading])
return {
data: state.data,
manager,
}
}