-
Notifications
You must be signed in to change notification settings - Fork 398
Expand file tree
/
Copy pathasync.tsx
More file actions
199 lines (173 loc) · 5.34 KB
/
async.tsx
File metadata and controls
199 lines (173 loc) · 5.34 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
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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
import debounce from 'lodash.debounce';
import PropTypes from 'prop-types';
import React, {
ChangeEvent,
ComponentType,
forwardRef,
ReactNode,
useCallback,
useEffect,
useRef,
} from 'react';
import useForceUpdate from '@restart/hooks/useForceUpdate';
import usePrevious from '@restart/hooks/usePrevious';
import Typeahead from '../core/Typeahead';
import { optionType } from '../propTypes';
import { getDisplayName, isFunction, warn } from '../utils';
import { TypeaheadComponentProps } from '../components/Typeahead';
import type { OptionType } from '../types';
const propTypes = {
/**
* Delay, in milliseconds, before performing search.
*/
delay: PropTypes.number,
/**
* Whether or not a request is currently pending. Necessary for the
* container to know when new results are available.
*/
isLoading: PropTypes.bool.isRequired,
/**
* Number of input characters that must be entered before showing results.
*/
minLength: PropTypes.number,
/**
* Callback to perform when the search is executed.
*/
onSearch: PropTypes.func.isRequired,
/**
* Options to be passed to the typeahead. Will typically be the query
* results, but can also be initial default options.
*/
options: PropTypes.arrayOf(optionType),
/**
* Message displayed in the menu when there is no user input.
*/
promptText: PropTypes.node,
/**
* Message displayed in the menu while the request is pending.
*/
searchText: PropTypes.node,
/**
* Whether or not the component should cache query results.
*/
useCache: PropTypes.bool,
};
export interface UseAsyncProps<Option extends OptionType> extends TypeaheadComponentProps<Option> {
delay?: number;
isLoading: boolean;
onSearch: (query: string) => void;
promptText?: ReactNode;
searchText?: ReactNode;
useCache?: boolean;
}
type Cache<Option extends OptionType> = Record<string, Option[]>;
interface DebouncedFunction extends Function {
cancel(): void;
}
/**
* Logic that encapsulates common behavior and functionality around
* asynchronous searches, including:
*
* - Debouncing user input
* - Optional query caching
* - Search prompt and empty results behaviors
*/
export function useAsync<Option extends OptionType>(props: UseAsyncProps<Option>) {
const {
allowNew,
delay = 200,
emptyLabel,
isLoading,
minLength = 2,
onInputChange,
onSearch,
options = [],
promptText = 'Type to search...',
searchText = 'Searching...',
useCache = true,
...otherProps
} = props;
const cacheRef = useRef<Cache<Option>>({});
const handleSearchDebouncedRef = useRef<DebouncedFunction | null>(null);
const queryRef = useRef<string>(props.defaultInputValue || '');
const forceUpdate = useForceUpdate();
const prevProps = usePrevious(props);
const handleSearch = useCallback(
(query: string) => {
queryRef.current = query;
if (!query || (minLength && query.length < minLength)) {
return;
}
// Use cached results, if applicable.
if (useCache && cacheRef.current[query]) {
// Re-render the component with the cached results.
forceUpdate();
return;
}
// Perform the search.
onSearch(query);
},
[forceUpdate, minLength, onSearch, useCache]
);
// Set the debounced search function.
useEffect(() => {
handleSearchDebouncedRef.current = debounce(handleSearch, delay);
return () => {
handleSearchDebouncedRef.current &&
handleSearchDebouncedRef.current.cancel();
};
}, [delay, handleSearch]);
useEffect(() => {
// Ensure that we've gone from a loading to a completed state. Otherwise
// an empty response could get cached if the component updates during the
// request (eg: if the parent re-renders for some reason).
if (!isLoading && prevProps && prevProps.isLoading && useCache) {
cacheRef.current[queryRef.current] = options;
}
});
const getEmptyLabel = () => {
if (!queryRef.current.length) {
return promptText;
}
if (isLoading) {
return searchText;
}
return emptyLabel;
};
const handleInputChange = useCallback(
(query: string, e: ChangeEvent<HTMLInputElement>) => {
onInputChange && onInputChange(query, e);
handleSearchDebouncedRef.current &&
handleSearchDebouncedRef.current(query);
},
[onInputChange]
);
const cachedQuery = cacheRef.current[queryRef.current];
return {
...otherProps,
// Disable custom selections during a search if `allowNew` isn't a function.
allowNew: isFunction(allowNew) ? allowNew : allowNew && !isLoading,
emptyLabel: getEmptyLabel(),
isLoading,
minLength,
onInputChange: handleInputChange,
options: useCache && cachedQuery ? cachedQuery : options,
};
}
/* istanbul ignore next */
export function withAsync<Option extends OptionType, T extends UseAsyncProps<Option> = UseAsyncProps<Option>>(
Component: ComponentType<T>
) {
warn(
false,
'Warning: `withAsync` is deprecated and will be removed in the next ' +
'major version. Use `useAsync` instead.'
);
const AsyncTypeahead = forwardRef<Typeahead<Option>, T>((props, ref) => (
<Component {...props} {...useAsync(props)} ref={ref} />
));
AsyncTypeahead.displayName = `withAsync(${getDisplayName(Component)})`;
// @ts-ignore
AsyncTypeahead.propTypes = propTypes;
return AsyncTypeahead;
}