-
Notifications
You must be signed in to change notification settings - Fork 0
/
counter-initial.js
79 lines (70 loc) · 1.91 KB
/
counter-initial.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
69
70
71
72
73
74
75
76
77
78
79
import { useCallback, useState } from 'react';
import { useSelector, useDispatch } from 'react-redux';
import {
decrement,
decrementByAmount,
increment,
incrementByAmount,
} from './counterSlice';
export default function Counter() {
const counter = useSelector((state) => state.counter.value);
const dispatch = useDispatch();
const [amount, setAmount] = useState(0);
const handleDecrement = useCallback(() => dispatch(decrement()), [dispatch]);
const handleIncrement = useCallback(() => dispatch(increment()), [dispatch]);
const handleSetAmountBy = useCallback((event) => {
const value = event.target.value;
const newAmount = value ? parseInt(event.target.value, 10) : '';
setAmount(newAmount);
}, []);
const handleDecrementByAmount = useCallback(
() => Number.isFinite(amount) && dispatch(decrementByAmount(amount)),
[dispatch, amount]
);
const handleIncrementByAmount = useCallback(
() => Number.isFinite(amount) && dispatch(incrementByAmount(amount)),
[dispatch, amount]
);
return (
<div className="container">
<main className="main">
<h1 className="title">{`Counter: ${counter}`}</h1>
<div className="grid">
<button className="btn" type="button" onClick={handleDecrement}>
-
</button>
<button className="btn" type="button" onClick={handleIncrement}>
+
</button>
</div>
<div className="grid">
<div className="amountWrapper">
<button
className="btn"
type="button"
onClick={handleDecrementByAmount}
>
- by amount
</button>
<label className="label">
<input
className="input"
type="number"
onChange={handleSetAmountBy}
value={amount}
required
/>
</label>
<button
className="btn"
type="button"
onClick={handleIncrementByAmount}
>
+ by amount
</button>
</div>
</div>
</main>
</div>
);
}