Skip to content

Instantly share code, notes, and snippets.

@jaredpalmer
Created September 6, 2017 15:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save jaredpalmer/205d8aa0244366e864200d31c1ad5214 to your computer and use it in GitHub Desktop.
Save jaredpalmer/205d8aa0244366e864200d31c1ad5214 to your computer and use it in GitHub Desktop.
import React from 'react';
class ReducerComponent extends React.Component {
constructor(props) {
super(props);
}
reducer = {};
dispatch = action =>
this.setState((state, props) => this.reducer[action](state, props));
}
// this can be defined anywhere
const counter = {
increment: (state, props) => ({ ...state, count: state++ }),
decrement: (state, props) => ({ ...state, count: state.count-- }),
}
class Counter extends ReducerComponent {
state = {
count: 0,
};
reducer = {
...counter, // nicer than combine reducer amirite?
reset: (state, props) => ({ ...state, count: 0 }),
};
render() {
return (
<div>
Counter: {this.state.count}
<button onClick={() => this.dispatch('increment')}>-</button>
<button onClick={() => this.dispatch('decrement')}>+</button>
<button onClick={() => this.dispatch('reset')}>Reset</button>
</div>
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment