Skip to content

Instantly share code, notes, and snippets.

@jaredpalmer
Created September 6, 2017 16:01
Show Gist options
  • Save jaredpalmer/ef2723b81c4322ca58bb9ccc5bc48446 to your computer and use it in GitHub Desktop.
Save jaredpalmer/ef2723b81c4322ca58bb9ccc5bc48446 to your computer and use it in GitHub Desktop.
import * as React from 'react';
class ReducerComponent<Props, State> extends React.Component<Props, State> {
constructor(props: Props) {
super(props);
}
reducer = (state: State, action: string) => {
// this should be
return state;
};
reduce = (action: string) => {
this.setState((prevState, prevProps) => this.reducer(prevState, action));
};
}
interface CounterState {
count: number;
}
export class Counter extends ReducerComponent<{}, CounterState> {
state = {
count: 0,
};
reducer = (state: CounterState, action: string) => {
switch (action) {
case 'increment':
return { ...state, count: state.count++ };
case 'decrement':
return { ...state, count: state.count-- };
case 'reset':
return { ...state, count: 0 };
default:
return state;
}
};
render() {
return (
<div>
Count: {this.state.count}
<button onClick={() => this.reduce('increment')}>-</button>
<button onClick={() => this.reduce('decrement')}>+</button>
<button onClick={() => this.reduce('reset')}>Reset</button>
</div>
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment