1
- import React , { Fragment , useState , useEffect } from 'react' ;
1
+ import React , {
2
+ Fragment ,
3
+ useState ,
4
+ useEffect ,
5
+ useReducer ,
6
+ } from 'react' ;
2
7
import axios from 'axios' ;
3
8
9
+ function dataFetchReducer ( state , action ) {
10
+ switch ( action . type ) {
11
+ case 'FETCH_INIT' :
12
+ return { ...state , isLoading : true , isError : false } ;
13
+ case 'FETCH_SUCCESS' :
14
+ return {
15
+ ...state ,
16
+ isLoading : false ,
17
+ isError : false ,
18
+ data : action . payload ,
19
+ } ;
20
+ case 'FETCH_FAILURE' :
21
+ return {
22
+ ...state ,
23
+ isLoading : false ,
24
+ isError : true ,
25
+ data : { hits : [ ] } ,
26
+ } ;
27
+ default :
28
+ throw new Error ( ) ;
29
+ }
30
+ }
31
+
4
32
const useDataApi = ( initialUrl , initialData ) => {
5
- const [ data , setData ] = useState ( initialData ) ;
6
33
const [ url , setUrl ] = useState ( initialUrl ) ;
7
- const [ isLoading , setIsLoading ] = useState ( false ) ;
8
- const [ isError , setIsError ] = useState ( false ) ;
34
+
35
+ const [ state , dispatch ] = useReducer ( dataFetchReducer , {
36
+ isLoading : false ,
37
+ isError : false ,
38
+ data : initialData ,
39
+ } ) ;
9
40
10
41
useEffect ( ( ) => {
11
42
const fetchData = async ( ) => {
12
- setIsError ( false ) ;
13
- setIsLoading ( true ) ;
43
+ dispatch ( { type : 'FETCH_INIT' } ) ;
14
44
15
45
try {
16
46
const result = await axios ( url ) ;
17
47
18
- setData ( result . data ) ;
48
+ dispatch ( { type : 'FETCH_SUCCESS' , payload : result . data } ) ;
19
49
} catch ( error ) {
20
- setIsError ( true ) ;
50
+ dispatch ( { type : 'FETCH_FAILURE' } ) ;
21
51
}
22
-
23
- setIsLoading ( false ) ;
24
52
} ;
25
53
26
54
fetchData ( ) ;
@@ -31,7 +59,7 @@ const useDataApi = (initialUrl, initialData) => {
31
59
event . preventDefault ( ) ;
32
60
} ;
33
61
34
- return { data , isLoading , isError , doGet } ;
62
+ return { ... state , doGet } ;
35
63
} ;
36
64
37
65
function App ( ) {
0 commit comments