Skip to content

Commit 003caf6

Browse files
committed
add useDataLoader function
1 parent 6a85e7c commit 003caf6

File tree

1 file changed

+58
-2
lines changed

1 file changed

+58
-2
lines changed

src/index.js

Lines changed: 58 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,59 @@
1-
export const useDataLoader = () => {
2-
// TODO implement
1+
import { useEffect, useState, useReducer } from 'react'
2+
3+
const reducer = (state, action) => {
4+
switch (action.type) {
5+
case 'get':
6+
return { ...state, loading: true }
7+
case 'success':
8+
return {
9+
...state,
10+
data: action.payload.data,
11+
error: null,
12+
loading: false,
13+
}
14+
case 'error':
15+
return {
16+
...state,
17+
data: null,
18+
error: action.payload.error,
19+
loading: false,
20+
}
21+
default:
22+
return state
23+
}
24+
}
25+
26+
export const useDataLoader = (getData, ...args) => {
27+
const [nonce, setNonce] = useState(Date.now())
28+
const [state, dispatch] = useReducer(reducer, {
29+
data: null,
30+
error: null,
31+
loading: true,
32+
})
33+
34+
useEffect(
35+
() => {
36+
let cancel = false
37+
38+
dispatch({ type: 'get' })
39+
getData(...args)
40+
.then(data => {
41+
!cancel && dispatch({ type: 'success', payload: { data } })
42+
})
43+
.catch(error => {
44+
!cancel && dispatch({ type: 'error', payload: { error } })
45+
})
46+
47+
return () => {
48+
cancel = true
49+
}
50+
},
51+
[nonce, ...args],
52+
)
53+
54+
const retry = () => {
55+
setNonce(Date.now())
56+
}
57+
58+
return { ...state, retry }
359
}

0 commit comments

Comments
 (0)