forked from tbleckert/react-select-search
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathuseOptions.js
40 lines (31 loc) · 991 Bytes
/
useOptions.js
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
import { useEffect, useState } from 'react';
import flattenOptions from './lib/flattenOptions';
export default function useOptions(
defaultOptions,
getOptions,
debounceTime,
search,
) {
const [options, setOptions] = useState(() => flattenOptions(defaultOptions));
const [fetching, setFetching] = useState(false);
useEffect(() => {
let timeout;
if (!getOptions) {
return;
}
timeout = setTimeout(() => {
const optionsReq = getOptions(search, options);
setFetching(true);
Promise.resolve(optionsReq)
.then((newOptions) => setOptions(flattenOptions(newOptions)))
.finally(() => setFetching(false));
}, debounceTime);
return () => {
clearTimeout(timeout);
};
}, [search]);
useEffect(() => {
setOptions(flattenOptions(defaultOptions));
}, [defaultOptions]);
return [options, fetching];
}