-
-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathApp.js
68 lines (54 loc) · 1.38 KB
/
App.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
57
58
59
60
61
62
63
64
65
66
67
68
import React from 'react';
import axios from 'axios';
export const dataReducer = (state, action) => {
if (action.type === 'SET_ERROR') {
return { ...state, list: [], error: true };
}
if (action.type === 'SET_LIST') {
return { ...state, list: action.list, error: null };
}
throw new Error();
};
const initialData = {
list: [],
error: null,
};
const App = () => {
const [counter, setCounter] = React.useState(0);
const [data, dispatch] = React.useReducer(dataReducer, initialData);
React.useEffect(() => {
axios
.get('http://hn.algolia.com/api/v1/search?query=react')
.then(response => {
dispatch({ type: 'SET_LIST', list: response.data.hits });
})
.catch(() => {
dispatch({ type: 'SET_ERROR' });
});
}, []);
return (
<div>
<h1>My Counter</h1>
<Counter counter={counter} />
<button type="button" onClick={() => setCounter(counter + 1)}>
Increment
</button>
<button type="button" onClick={() => setCounter(counter - 1)}>
Decrement
</button>
<h2>My Async Data</h2>
{data.error && <div className="error">Error</div>}
<ul>
{data.list.map(item => (
<li key={item.objectID}>{item.title}</li>
))}
</ul>
</div>
);
};
export const Counter = ({ counter }) => (
<div>
<p>{counter}</p>
</div>
);
export default App;