Skip to content

Commit 3041130

Browse files
committed
feat: 🎸 added counter with reducer
1 parent 42a9baf commit 3041130

File tree

3 files changed

+44
-2
lines changed

3 files changed

+44
-2
lines changed

2024 Prep/machine_coding/react/src/App.tsx

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,11 @@
11
import './App.css'
2-
import { InputHookComp } from './components'
2+
import { CounterWithReducer } from './components'
33

44
function App() {
55
return (
66
<div className="container">
77
<h1>Vite + React</h1>
8-
<InputHookComp />
8+
<CounterWithReducer />
99
</div>
1010
)
1111
}
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
import { useReducer } from 'react'
2+
3+
export default function CounterWithReducer() {
4+
const counterReducer = (state, action: { type: string }) => {
5+
switch (action.type) {
6+
case 'increment': {
7+
return { count: state.count + 1 }
8+
}
9+
10+
case 'decrement': {
11+
return { count: state.count - 1 }
12+
}
13+
default:
14+
return
15+
}
16+
}
17+
const initialState = {
18+
count: 0,
19+
}
20+
const [state, dispatch] = useReducer(counterReducer, initialState)
21+
22+
const onUpdateCounter = (type: string) => {
23+
dispatch({ type })
24+
}
25+
26+
return (
27+
<div
28+
style={{
29+
display: 'grid',
30+
placeContent: 'center',
31+
}}
32+
>
33+
<h2>Counter With Reducer</h2>
34+
<h4>counter: {state?.count}</h4>
35+
36+
<button onClick={() => onUpdateCounter('increment')}>Increment +</button>
37+
<button onClick={() => onUpdateCounter('decrement')}>Decrement -</button>
38+
</div>
39+
)
40+
}

2024 Prep/machine_coding/react/src/components/index.ts

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import BatchingStates from './BatchingStates'
55
import CountDownTimer from './Timer'
66
import LiftingUpState from './LiftingStateUp'
77
import InputHookComp from './InputCustomHookComp'
8+
import CounterWithReducer from './CounterWithReducer'
89

910
export {
1011
Loader,
@@ -14,4 +15,5 @@ export {
1415
CountDownTimer,
1516
LiftingUpState,
1617
InputHookComp,
18+
CounterWithReducer,
1719
}

0 commit comments

Comments
 (0)