Last active
September 19, 2017 15:43
-
-
Save elias551/69263782a66d5c73c3b77450096c7724 to your computer and use it in GitHub Desktop.
Minimal redux-typescript format
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"; | |
import * as ReactDOM from "react-dom"; | |
import { createStore, Action, Dispatch } from "redux"; | |
import { Provider, connect } from "react-redux"; | |
enum ActionType { | |
Increment = "INCREMENT", | |
Decrement = "DECREMENT" | |
} | |
interface AppAction extends Action { | |
type: ActionType; | |
} | |
const increment = () => ({ | |
type: ActionType.Increment | |
}); | |
const decrement = () => ({ | |
type: ActionType.Decrement | |
}); | |
interface ReduxState { | |
value: number; | |
} | |
const initialState: ReduxState = { value: 0 }; | |
const reducer = (state: ReduxState = initialState, action: AppAction) => { | |
switch (action.type) { | |
case ActionType.Increment: | |
return { value: state.value + 1 }; | |
case ActionType.Decrement: | |
return { value: state.value - 1 }; | |
default: | |
return state; | |
} | |
}; | |
interface ComponentProps { | |
value: number; | |
increment: () => void; | |
decrement: () => void; | |
} | |
const App: React.StatelessComponent<ComponentProps> = props => { | |
return ( | |
<div> | |
The value is: {props.value} | |
<br /> | |
<button onClick={props.increment}>increment</button> | |
<br /> | |
<button onClick={props.decrement}>decrement</button> | |
</div> | |
); | |
}; | |
const mapStateToProps = (state: ReduxState) => state; | |
const mapDispatchToProps = (dispatch: Dispatch<ReduxState>) => ({ | |
increment: () => { | |
dispatch(increment()); | |
}, | |
decrement: () => { | |
dispatch(decrement()); | |
} | |
}); | |
const AppComponent = connect(mapStateToProps, mapDispatchToProps)(App); | |
const store = createStore(reducer); | |
ReactDOM.render( | |
<Provider store={store}> | |
<AppComponent /> | |
</Provider>, | |
document.getElementById("root") as HTMLElement | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment