Skip to content

Commit 4d3bb1c

Browse files
committed
introduce reducer
1 parent 756a410 commit 4d3bb1c

File tree

1 file changed

+39
-11
lines changed

1 file changed

+39
-11
lines changed

src/useDataApiHook-example/index.js

Lines changed: 39 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,26 +1,54 @@
1-
import React, { Fragment, useState, useEffect } from 'react';
1+
import React, {
2+
Fragment,
3+
useState,
4+
useEffect,
5+
useReducer,
6+
} from 'react';
27
import axios from 'axios';
38

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+
432
const useDataApi = (initialUrl, initialData) => {
5-
const [data, setData] = useState(initialData);
633
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+
});
940

1041
useEffect(() => {
1142
const fetchData = async () => {
12-
setIsError(false);
13-
setIsLoading(true);
43+
dispatch({ type: 'FETCH_INIT' });
1444

1545
try {
1646
const result = await axios(url);
1747

18-
setData(result.data);
48+
dispatch({ type: 'FETCH_SUCCESS', payload: result.data });
1949
} catch (error) {
20-
setIsError(true);
50+
dispatch({ type: 'FETCH_FAILURE' });
2151
}
22-
23-
setIsLoading(false);
2452
};
2553

2654
fetchData();
@@ -31,7 +59,7 @@ const useDataApi = (initialUrl, initialData) => {
3159
event.preventDefault();
3260
};
3361

34-
return { data, isLoading, isError, doGet };
62+
return { ...state, doGet };
3563
};
3664

3765
function App() {

0 commit comments

Comments
 (0)