-
Notifications
You must be signed in to change notification settings - Fork 20
/
WithReducer.js
68 lines (60 loc) · 1.51 KB
/
WithReducer.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";
const allData = new Array(25).fill(0).map((_val, i) => i + 1);
const perPage = 10;
const types = {
start: "START",
loaded: "LOADED"
};
const reducer = (state, action) => {
switch (action.type) {
case types.start:
return { ...state, loading: true };
case types.loaded:
return {
...state,
loading: false,
data: [...state.data, ...action.newData],
more: action.newData.length === perPage,
after: state.after + action.newData.length
};
default:
throw new Error("Don't understand action");
}
};
function App() {
const [state, dispatch] = React.useReducer(reducer, {
loading: false,
more: true,
data: [],
after: 0
});
const { loading, data, after, more } = state;
return (
<div className="App">
<ul>
{data.map(row => (
<li key={row} style={{ background: "orange" }}>
{row}
</li>
))}
{loading && <li>Loading...</li>}
{!loading && more && (
<li style={{ background: "green" }}>
<button
onClick={() => {
dispatch({ type: types.start });
setTimeout(() => {
const newData = allData.slice(after, after + perPage);
dispatch({ type: types.loaded, newData });
}, 1000);
}}
>
Load More
</button>
</li>
)}
</ul>
</div>
);
}
export default App;