-
Notifications
You must be signed in to change notification settings - Fork 7
/
index.ts
43 lines (35 loc) · 979 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
39
40
41
42
43
import { to } from 'await-to-js';
import { useEffect, useReducer } from 'react';
import { debounce } from '@src/lib/utils/debounce';
import { reducer } from './reducer';
import { Action, State } from './types';
function useStackedFetchBase<T>(
willFetch: () => Promise<T[]>,
isInitialFetching: boolean,
): State<T> {
const [state, dispatch] = useReducer<React.Reducer<State<T>, Action<T>>>(reducer, {
_TAG: 'IDLE',
data: [],
});
useEffect(() => {
const fetchList = debounce(async () => {
dispatch({
_TAG: 'FETCH',
isInitialFetching,
});
const [error, response] = await to(willFetch());
if (error) {
return dispatch({
_TAG: 'FAILED',
error,
});
}
if (response) {
dispatch({ _TAG: 'SUCCESS', isInitialFetching, data: response });
}
});
fetchList();
}, [willFetch, isInitialFetching]);
return state;
}
export default useStackedFetchBase;