File tree Expand file tree Collapse file tree 1 file changed +58
-2
lines changed Expand file tree Collapse file tree 1 file changed +58
-2
lines changed Original file line number Diff line number Diff line change 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}
You can’t perform that action at this time.
0 commit comments