-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
56 lines (50 loc) · 1.42 KB
/
index.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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
import { useReducer, useCallback } from 'react'
const FETCH_REQUEST = 'FETCH_REQUEST'
const FETCH_SUCCESS = 'FETCH_SUCCESS'
const FETCH_FAILURE = 'FETCH_FAILURE'
const fetchDataReducer = (initState, action) => {
switch (action.type) {
case FETCH_REQUEST:
return {
data: null,
...initState,
isLoading: true,
error: null,
}
case FETCH_SUCCESS:
return {
...initState,
isLoading: false,
error: null,
data: action.payload,
}
case FETCH_FAILURE:
return {
...initState,
isLoading: false,
error: action.error,
}
default:
throw new Error()
}
}
/**
* @param {*} requestFn custom fetch function, e.g: (data) => axios('/xxx', data)
* @param {*} initState setInit state, defaultValue: undefined
* @return {array} [state, memoizedFetchDateApi] state: { data, isLoading, error, ... }
*/
const useFetchData = (requestFn, initState) => {
const [state, dispatch] = useReducer(fetchDataReducer, initState)
const fetchData = async (params) => {
dispatch({ type: FETCH_REQUEST })
try {
const result = await requestFn(params)
dispatch({ type: FETCH_SUCCESS, payload: result })
} catch (error) {
dispatch({ type: FETCH_FAILURE, error })
}
}
const memoizedFetchDateApi = useCallback(fetchData, [])
return [state || {}, memoizedFetchDateApi]
}
export default useFetchData