Skip to content

Commit

Permalink
React Hooks useReducer (complex state & action)
Browse files Browse the repository at this point in the history
  • Loading branch information
Omid-Sargazi committed May 28, 2024
1 parent 38337ba commit a42a8e5
Showing 1 changed file with 20 additions and 2 deletions.
22 changes: 20 additions & 2 deletions src/Components/useReducer/CounterByReducerTwo.js
Original file line number Diff line number Diff line change
@@ -1,14 +1,25 @@
import { useReducer } from "react";
const initialState = {
firstCounter: 0,
secondCounter: 10,
};
const reducer = (state, action) => {
switch (action.type) {
case "inc":
return { firstCounter: state.firstCounter + action.value };
return {
...state,
firstCounter: state.firstCounter + action.value,
};
case "inc2":
return { ...state, secondCounter: state.secondCounter + action.value };
case "dec2":
return { ...state, secondCounter: state.secondCounter - action.value };

case "dec":
return { firstCounter: state.firstCounter - action.value };
return {
...state,
firstCounter: state.firstCounter - action.value,
};

case "reset":
return initialState;
Expand All @@ -23,6 +34,7 @@ const CounterByReducerTwo = () => {
<>
<h2>CounterByReducerTwo</h2>
<h1>CountTwo: {count.firstCounter}</h1>
<h1>CountTwo: {count.secondCounter}</h1>
<button onClick={() => dispatch({ type: "inc", value: 1 })}>
Increment
</button>
Expand All @@ -34,6 +46,12 @@ const CounterByReducerTwo = () => {
<button onClick={() => dispatch({ type: "dec", value: 1 })}>
Decrement
</button>
<button onClick={() => dispatch({ type: "inc2", value: 1 })}>
IncSecond
</button>
<button onClick={() => dispatch({ type: "dec2", value: 1 })}>
DecSecond
</button>
</>
);
};
Expand Down

0 comments on commit a42a8e5

Please sign in to comment.