Last active
April 9, 2019 00:20
-
-
Save treyhuffine/fb2c56f62383c15b382f8ac00ddd5483 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import * as React from 'react'; | |
enum ActionType { | |
Increment = 'increment', | |
Decrement = 'decrement', | |
} | |
interface IState { | |
count: number; | |
} | |
interface IAction { | |
type: ActionType; | |
payload: { | |
count: number; | |
}; | |
} | |
const initialState: IState = {count: 0}; | |
const reducer: React.Reducer<IState, IAction> = (state, action) => { | |
switch (action.type) { | |
case ActionType.Increment: | |
return {count: state.count + action.payload.count}; | |
case ActionType.Decrement: | |
return {count: state.count - action.payload.count}; | |
default: | |
throw new Error(); | |
} | |
} | |
const ComplexState = () => { | |
const [state, dispatch] = React.useReducer<React.Reducer<IState, IAction>>(reducer, initialState); | |
return ( | |
<div> | |
<div>Count: {state.count}</div> | |
<button onClick={ | |
() => dispatch({type: ActionType.Increment, payload: { count: 1 } }) | |
}>+</button> | |
<button onClick={ | |
() => dispatch({type: ActionType.Decrement, payload: { count: 1 }}) | |
}>-</button> | |
</div> | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment