Created
November 25, 2015 02:23
-
-
Save namelos/8fb32f8dbc0c4040c5b3 to your computer and use it in GitHub Desktop.
This file contains 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 React, { Component } from 'react'; | |
import { render } from 'react-dom'; | |
import { createStore, applyMiddleware, bindActionCreators, combineReducers } from 'redux'; | |
import thunk from 'redux-thunk'; | |
import { Provider, connect } from 'react-redux'; | |
import { Map } from 'immutable' | |
import createLogger from 'redux-logger' | |
const logger = createLogger() | |
// Actions | |
const inc = () => ({ type: 'INC' }); | |
const dec = () => ({ type: 'DEC' }); | |
const incIfOdd = () => (dispatch, getState) => { | |
const { counter } = getState(); | |
const current = (counter.getIn('x')) | |
if (current % 2 === 0) { | |
return; | |
} | |
dispatch(inc()); | |
} | |
const incAsync = (delay = 1000) => dispatch => setTimeout(() => dispatch(inc()), delay); | |
// Reducer | |
const counter = (state = Map({ x: 0 }), action) => { | |
switch (action.type) { | |
case 'INC': | |
return state.update('x', x => x + 1) | |
case 'DEC': | |
return state.update('x', x => x + 1) | |
default: | |
return state | |
} | |
} | |
const reducer = combineReducers({ | |
counter | |
}); | |
const store = applyMiddleware(logger, thunk)(createStore)(reducer); | |
// Component | |
// New syntax in 0.14 for pure render component | |
// parameter `props` could be deconstructured as following: | |
// Awesome! | |
const Counter = ({ counter, inc, dec, incIfOdd, incAsync }) => <p> | |
Clicked: { counter } times | |
{' '} | |
<button onClick={ inc }>+</button> | |
{' '} | |
<button onClick={ dec }>-</button> | |
{' '} | |
<button onClick={ incIfOdd }>IncIfOdd</button> | |
{' '} | |
<button onClick={ () => incAsync() }>Async</button> | |
</p> | |
// Container | |
const stateToProps = ({ counter }) => ({ counter: counter.get('x') }); | |
const dispatcherToProps = dispatch => bindActionCreators({ inc, dec, incIfOdd, incAsync }, dispatch); | |
const App = connect(stateToProps, dispatcherToProps)(Counter); | |
// render | |
render( | |
<Provider store={store}> | |
<App /> | |
</Provider>, | |
document.getElementById('root') | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment