Skip to content

Instantly share code, notes, and snippets.

@nickjohnson-dev
Created August 21, 2015 03:18
Show Gist options
  • Save nickjohnson-dev/050e64557f374213ccf2 to your computer and use it in GitHub Desktop.
Save nickjohnson-dev/050e64557f374213ccf2 to your computer and use it in GitHub Desktop.
Playing with Asynchronous Redux + React
import { createAction } from 'redux-actions';
export const setCount = createAction('SET_COUNT');
export const decrementCount = createAction('DECREMENT_COUNT');
export const incrementCount = createAction('INCREMENT_COUNT');
export const delayedIncrementCount = (step) =>
incrementCount(new Promise(resolve => {
setTimeout(() => {
resolve(step)
}, 2000);
}))
import { combineReducers } from 'redux';
import { handleActions } from 'redux-actions';
const count = handleActions({
SET_COUNT: (state, action) =>
action.payload,
DECREMENT_COUNT: (state, action) =>
state - (action.payload || 1),
INCREMENT_COUNT: (state, action) =>
state + (action.payload || 1)
}, 0);
export default combineReducers({
count
});
import { createStore, applyMiddleware } from 'redux';
import loggerMiddleware from 'redux-logger';
import promiseMiddleware from 'redux-promise';
import appReducer from './app-reducer';
const createStoreWithMiddleware = applyMiddleware(
loggerMiddleware,
promiseMiddleware
)(createStore);
export default createStoreWithMiddleware(appReducer);
import React from 'react';
import { connect } from 'react-redux';
import {
decrementCount,
incrementCount,
delayedIncrementCount
} from './app-actions';
export default connect(
state => ({
count: state.count
}),
dispatch => ({
decrementCount: step =>
dispatch(decrementCount(step)),
incrementCount: step =>
dispatch(incrementCount(step)),
delayedIncrementCount: step =>
dispatch(delayedIncrementCount(step))
})
)(React.createClass({
displayName: 'App',
propTypes: {
count: React.PropTypes.number.isRequired,
decrementCount: React.PropTypes.func.isRequired,
incrementCount: React.PropTypes.func.isRequired,
delayedIncrementCount: React.PropTypes.func.isRequired
},
render() {
return (
<div>
<h1>
Count: {this.props.count}
</h1>
<button
type="button"
onClick={this.increment}>
Increment
</button>
<button
type="button"
onClick={this.decrement}>
Decrement
</button>
</div>
);
},
increment() {
this.props.delayedIncrementCount(10);
},
decrement() {
this.props.decrementCount(10);
}
}));
import React from 'react';
import { Provider } from 'react-redux';
import store from './app-store';
import App from './App';
React.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